mongodb - 如何在 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"
}
})
解决方案
当您使用 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']]}}}])
推荐阅读
- image - Docker 镜像向上兼容
- python-3.x - 如何检查 Invar() 的空条目
- django - appengine/Django 使用类提交表单
- arrays - Loop over data object Vuejs to create a menu
- python - 使用python的split函数后奇怪的解码(例如:\x00)
- vb.net - OracleCommand ExecuteNonQuery with Async
- rest - Preventing API calls from uwanted internal services/journeys
- azure - How do I write a docker file to use the PORT environment variable in Azure App Service
- javascript - Service Worker / Safari / fetch 事件在消息事件之前触发
- node.js - nodejs.How do subprocess destroyed along with the masterprocess?