Is there any way to updateMany a collection where the filter is a IN condition from another collection.
In SQL it would be :
UPDATE collection1
SET field1 = true
WHERE _id IN (SELECT _id FROM collection2)
Input collections
collection1 : [{"_id" : "1", "field1": false}, {"_id" : "2", "field1": false} ]
collection2 : [{"_id" : "1"}, {"_id" : "3"}]
Expected result
collection1 : [{"_id" : "1", "field1": true}, {"_id" : "2", "field1": false} ]
Based on @ray comment here is my finding.
You can use an aggregation pipeline with a $merge
into the current collection using whenMatched: 'replace'
and whenNotMatched: 'discard'
db.collection1.aggregate([
{
$lookup: {
from: 'collection2',
localField: '_id ',
foreignField: '_id',
as: 'collection2_docs'
}
},
{
//SIMULATE THE INNER JOIN
$unwind: "$collection2_docs"
},
{
//Update the field
$set: {
"field1": true
}
},
{
//REMOVE THE lookup projection
$project: {
collection2_docs: 0
}
},
{
// Merge into the current collection using whenMatched: 'replace and whenNotMatched: 'discard'
$merge: {
into: 'collection1',
whenMatched: 'replace',
whenNotMatched: 'discard'
}
}
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.