首页 > 解决方案 > 如何在 MongoDB 更新中将字段的值推送到同一文档的另一个数组字段中

问题描述

我有一个 mongodb 对象,如下所示:

{
    "_id" : ObjectId("5e54934b2dfddc1826223bbb"),
    "sellProducts" : {
        "products" : []
    },
    "sellServices" : {
        "services" : []
    },
    "categories" : [],
    "status" : "Published",
    "tags" : [],
    "dateRange" : [],
    "membershipRequired" : false,
    "usersAttending" : [],
    "cities" : [],
    "companies" : [ 
        ObjectId("5db1c84ec10c45224c4b95fd"),
    ],
    "companyId" : ObjectId("5db1c84ec10c45224c4b95fd"),
    "jobProfile" : [ 
        ObjectId("5e549339a3ad20c97b7b0c7d")
    ],
    "fundingBy" : []
}

现在我想通过将companyId字段的值推送到公司数组中来更新相同的记录。我怎样才能做到这一点?

我尝试了以下查询,但没有用:

db.getCollection('posts').update({_id: ObjectId("5e54934b2dfddc1826223bbb")},
    {
        $push: 
            {
                companies: "$$companyId"
            }
    })

标签: mongodbmongodb-query

解决方案


当您使用 MongoDB 版本4.2时,您可以在更新中实际运行聚合管道,请尝试以下查询:

/** As `$push` doesn't work in aggregation as update operator
 * You can use `$addFields` or `$set` to re-create 'companies' field by merging 'companies' array with array converted 'companyId' field
 * which would leave 'companies' as an array with existing elements + companyId */

db.getCollection('posts').updateOne({_id: ObjectId("5e54934b2dfddc1826223bbb")},
         [{$addFields : {companies: {$concatArrays: ['$companies',['$companyId']]}}}])

推荐阅读