Hi,
I’m still getting to grips with the aggregation pipeline and need a bit of help understanding how I would piece together the following data:
I have a collection of ‘users’ that has a nested document called ‘roles’ within it. A user can belong to one or many ‘schools’ and with each school have a different set of ‘roles’. Here’s how I’ve structured the data:
User:
name,
email,
schools: [
{
roles: ['admin', 'user'],
schoolId: ObjectId(...)
}
]
A school looks like this:
_id,
name,
address
etc etc
What I would like to be able to do is produce a result that looks like this whenever I lookup a user:
name,
email,
schools: [
{
roles: ['admin', 'user'],
school: {
_id: ObjectId,
name,
...all other fields
}
}
]
Looking at the aggregation pipeline it seems like $lookup is my first port of call using something like this:
{
from: "schools",
as: "schools",
'let': { 'schoolId': '$roles.schoolId' },
'pipeline': [
{ '$match': { '$expr': { '$in': ['$_id', '$$schoolId'] } } }
],
'as':'schools'
}
Which, if I’m understanding correctly is great and gives me a ‘schools’ set of documents at the root level. I’m a bit stuck on how I get these documents to merge with the actual roles segment though. I’m also unclear about the need for a $match to check for existence.
I’d really appreciate any corrections/examples and comments.
J