I have a collection called X which holds a single document that looks like this:
{
"uid": "dfdf"
}
I have another collection called Y which also holds a single document that looks like this:
{
"name": "bfbf"
}
I want to add to the document from collection Y, the field and value from collection X so it will look like this:
{
"uid": "dfdf",
"name": "bfbf"
}
I ran the next code on the Y collection:
{$set : {"uid" : {"$query": {"$q": {}, "$ns": "**X**", "$p": "uid"}}}}
BUT the value is set with array like this:
{
"uid": ["dfdf"],
"name": "bfbf"
}
How can I set the original value without the array? Thanks in advance
CodePudding user response:
It seems that OP simply want to do uncontional lookup and assign the field uid
into the collection Y
db.Y.aggregate([
{
"$lookup": {
"from": "X",
"pipeline": [],
"as": "x"
}
},
{
"$unwind": "$x"
},
{
$set: {
"uid": "$x.uid"
}
},
{
"$unset": "x"
}
]).forEach(function(doc){
db.Y.update({_id: doc._id}, {$set: {uid: doc.uid}});
});
Here is the Mongo playground for your reference.