I have a meetup clone for practice with mongodb. I am interested in the $lookup
stage of the mongodb aggregation. I have a denormalized document that looks like this:
{
_id: ObjectId(),
createdAt: ISODate(),
description: "Group for people who like kittens",
members: [ ObjectId(), ObjectId() ]
}
My aim is to look up the members
from the collection users
and join them simply like so:
{
_id: ObjectId(),
createdAt: ISODate(),
description: "Group for people who like kittens.",
members: [{
_id: ObjectId(),
name: "Jeff"
}, {
_id: ObjectId(),
name: "Tim"
}]
}
When I try to do $lookup
on the array, it yields no results, so I do $unwind
which gives me several documents that I have to group.
db.meetups.aggregate([
{ $match: { "_id": id } },
{ $unwind: "$users" },
{
$lookup: {
from: "members",
localField: "users",
foreignField: "_id",
as: "members"
}
},
{
$group: {
_id: "$_id",
members: { $push: "$members" }
}
}
], /** ... */);
The problem is that this always yields an array with a single element, because I only ever expect one element. I've tried using the $group
operator, but then it is just an array filled with single element arrays rather than a series of objects
How is this done with mongo 3.2?