我有一个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"
}
})
当您使用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']]}}}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句