[英]How to update document in Mongodb collection with a field value from another collection
[英]MongoDB aggregation - replace field in collection from value in another collection
所以我有一个这样的收藏
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
value : true
和一个这样的
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
otherValue : false
如何使用聚合管道使用基于_id
的第一个集合中的value
更新第二个集合otherValue
我试过使用查找,然后像这样放松
{
from: 'col1',
localField: 'otherValue',
foreignField: 'value',
as: 'data'
}
然后放松
{
path: '$val'
}
但我不太确定 go 从这里到哪里,任何帮助将不胜感激。
尝试这个:
db.collection1.aggregate([
{
$lookup: {
from: "collection2",
let: { c1_id: "$_id", value: "$value" },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$c1_id"] }
}
},
{
$addFields: { otherValue: "$$value" }
}
],
as: "data"
}
},
{
$unwind: "$data"
}
])
Output:
{
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"value" : true,
"data" : {
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"otherValue" : true
}
}
其中collection1
是:
{
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"value" : true
}
其中collection2
是:
{
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"otherValue" : false
}
您可以使用$merge聚合阶段。
db.collection.aggregate([
{$match: { filter to pick the documents }},
{$lookup: {
from: "otherCollection"
localField: "_id",
foreignField: "_id",
as: "otherDocument"
}},
{$unwind: "$otherDocument"},
{$addFields:{
"otherDocument.otherValue": "$value"
}},
{$replaceRoot: {newRoot: "$otherDocument"}},
{$merge: {
into: "otherCollection",
on: "_id",
whenMatched: "replace",
whenNotMatched: "insert"
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.