In my mongodb books
collection I have documents that look like:
{
_id: ObjectId(625efa44f1ba751c8275ea51),
contributors:[ObjectId(625efa44f1ba751c8275ea52), ObjectId(625efa44f1ba751c8275ea53)]
//other fields
}
And I want to do a query that returns me documents like:
{
_id: ObjectId(625efa44f1ba751c8275ea51),
contributors:[
{
_id: ObjectId(625efa44f1ba751c8275ea52),
first_name: 'Luigi'
//many other fields
},
{
_id: ObjectId(625efa44f1ba751c8275ea53),
first_name: 'Mario'
//many other fields
},
]
//other fields
}
I did an unwind
on contributors and a lookup
with my users
collection and now I need to group them. I haven't used it before but I did something like:
{
$group:{
_id: '_id'
}
}
But I don't know what to do next in order to preserve all the fields from books and also from users.
Do you have any idea?
CodePudding user response:
If the $lookup
result is small enough (<16MB document size limit),
you can simply do a $lookup
.
db.books.aggregate([
{
"$lookup": {
"from": "users",
"localField": "contributors",
"foreignField": "_id",
"as": "contributors"
}
}
])
Here is the Mongo Playground for your reference.
If the $lookup
result will exceed 16 MB limit, you can still $unwind. Just use
$firstto regroup the other fields after the
$unwind`
db.books.aggregate([
{
"$lookup": {
"from": "users",
"localField": "contributors",
"foreignField": "_id",
"as": "contributors"
}
},
{
"$unwind": "$contributors"
},
{
"$group": {
"_id": "_id",
bookName: {
$first: "$bookName"
},
"contributors": {
"$push": "$contributors"
}
}
}
])
Here is the Mongo playground for your reference.