I have 2 collections like this:
//collection1
[{
Name: 'abc'
},
{
Name: 'def'
}]
// collection2
[{
Name: 'abc'
PresentInCollection1: '' // this field should be true since collection2.Name exists in collection1.Name
},
{
Name: 'xyz'
PresentInCollection1: '' // this field should be false since collection2.Name does not exists in collection1.Name
}]
I wanted to $set the value collection2.PresentInCollection1 to true when the collection2.Name matches with collection1.Name. Here is what I have tried:
db.stocks.update({}, [{
$lookup: {
from: 'collection1',
localField: 'Name',
foreignField: 'Name',
as: 'Match',
},
},
{
$set: {
PresentInCollection1: {
$cond: [{
$eq: ["Name", "$Match.Name"]
},
true,
false
]
},
},
},
]);
It throws the error:
"$lookup is not allowed to be used within an update"
Another approach is updating documents iteratively but I wanted to do this in one go. I'm thinking of MongoDB's $map - $reduce but unable to think of the query :)