所以我有一个这样的收藏
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
value : true
还有这样的
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
otherValue : false
如何使用聚合管道根据 otherValue
使用第一个集合中的 value
更新第二个集合 _id
我试过使用查找然后像这样放松
{
from: 'col1',
localField: 'otherValue',
foreignField: 'value',
as: 'data'
}
然后放松
{
path: '$val'
}
但我不太确定从哪里开始,任何帮助将不胜感激。
答案 0 :(得分:1)
试试这个:
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"
}
])
输出:
{
"_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
}
答案 1 :(得分:0)
您可以使用 $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"
}}
])