Query1: i was trying to combine two collection with selected field of both collections using mongodb Aggregate $lookup as follows
db.col1.aggregate([
{
Your $lookup
stage simply returns multiple entries in the user
field which then get flattened into individual subdocuments that have the same _id
value. You can validate this by replacing the $out
stage with a $match
instead:
db.col1.aggregate([{
$match: { _id: ObjectId('5b16305d145a5117552836ec') }
}
The key here is to understand how $unwind
works. Imagine you have the following document:
{
_id: 1,
users: [ 'a', 'b' ]
}
Once you $unwind
this you will get the following two documents:
{
_id: 1,
users: 'a'
},
{
_id: 1,
users: 'b'
}
So you get the same _id
value for two different documents!
Now, when you specify _id: 0
in your projection you remove the _id
field from all documents which will cause MongoDB to automatically create new _id
s which of course then works.