首页 > 解决方案 > mongodb:如何将特定字段从一个集合移动到另一个集合?

问题描述

我需要将 users,allocatedHours,_id 字段从 workname 集合中分离出来,以将其插入到 workstat 集合中。

db.workname.find().pretty()
{
     "_id":ObjectId("5d9fd8773d598088d2ea5e49")
     "role" : "Developer",
    "status" : "New",
    "title" : "CountySales",
    "desc" : "<p>Countysales</p>",
    "allocatedHours" : 480,
    "priority" : "Medium",
    "reqType" : "New",
    "users" : {
            "assigned" : [
                {
                    "isStatus" : "active",
                    "assignedDate" : ISODate("2020-11-16T12:24:56Z"),
                    "userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
                }
            ],
            "follower" : [
                {
                    "isStatus" : "active",
                    "followerDate" : ISODate("2020-11-16T12:24:56Z"),
                    "userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
                }
            ],
    }
}

我需要将该字段移动到 workstat 集合中。我需要在聚合查询中执行此操作。我需要为多个文档执行此操作。

 db.workedstat.find().pretty()
    "workId": ObjectId("5d9fd8773d598088d2ea5e49"),
    "allocatedHours" : 480,
    "users" : {
            "assigned" : [
                {
                    "isStatus" : "active",
                    "assignedDate" : ISODate("2020-11-16T12:24:56Z"),
                    "userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
                }
            ],
            "follower" : [
                {
                    "isStatus" : "active",
                    "followerDate" : ISODate("2020-11-16T12:24:56Z"),
                    "userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
                }
            ],
    }

标签: mongodbaggregation

解决方案


会是这样的:

db.workname.aggregate([
   { $project: { users: 1, allocatedHours: 1, _id: 1 } },
   { $merge: { into: "workedstat" } }
])

推荐阅读