Reputation: 515
so i've got a collection like so
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
value : true
and one like this
_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
otherValue : false
How can i use aggregation pipelines to update the second collection otherValue
with the value
from the first collection based on _id
I've tried using lookup and then unwind like
{
from: 'col1',
localField: 'otherValue',
foreignField: 'value',
as: 'data'
}
and then unwind
{
path: '$val'
}
But im not quite sure where to go from here, any help would be greatly appreciated.
Upvotes: 0
Views: 2288
Reputation: 28316
You might use the $merge aggregation stage.
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"
}}
])
Upvotes: 0
Reputation: 4452
Try this:
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
}
}
Where collection1
is:
{
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"value" : true
}
Where collection2
is:
{
"_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
"otherValue" : false
}
Upvotes: 1