I would like to aggregate building with floors and rooms:
Given the following 3 collections:
/* buildings */
{
"_id" : ObjectId("59a09abe388f595b15bb5fa6"),
"name" : "home"
}
/* floors */
{
"_id" : ObjectId("59a09abe388f595b15bb5fa3"),
"buildingId" : ObjectId("59a09abe388f595b15bb5fa6"),
"name" : "upstairs"
}
{
"_id" : ObjectId("59a09abe388f595b15bb5fa2"),
"buildingId" : ObjectId("59a09abe388f595b15bb5fa6"),
"name" : "downstairs"
}
/* rooms */
{
"_id" : ObjectId("59a09bce388f595b15bb5fb6"),
"floorId" : ObjectId("59a09abe388f595b15bb5fa3"),
"name" : "bathroom",
"_userId" : ObjectId("590a08dba07c1a1bee87b310")
}
{
"_id" : ObjectId("59a09bce388f595b15bb5fc6"),
"floorId" : ObjectId("59a09abe388f595b15bb5fa3"),
"name" : "living room",
"_userId" : ObjectId("590a08dba07c1a1bee87b310")
}
I would like to lookup them together and tried it with the following query:
db.getCollection('buildings').aggregate([
{
"$lookup": {
"from": "floors",
"localField": "_id",
"foreignField": "buildingId",
"as": "floors"
}
},
{
"$lookup": {
"from": "rooms",
"localField": "floors._id",
"foreignField": "floorId",
"as": "floors.rooms"
}
}
]);
This gives the following result:
{
"_id" : ObjectId("59a09abe388f595b15bb5fa6"),
"_userId" : ObjectId("590a08dba07c1a1bee87b310"),
"name" : "home",
"floors" : {
"rooms" : []
}
}
But I would have the following result:
{
"_id" : ObjectId("59a09abe388f595b15bb5fa6"),
"_userId" : ObjectId("590a08dba07c1a1bee87b310"),
"name" : "home",
"floors" : [
{
"_id" : ObjectId("59a09abe388f595b15bb5fa3"),
"buildingId" : ObjectId("59a09abe388f595b15bb5fa6"),
"name" : "upstairs",
"rooms": [
{
"_id" : ObjectId("59a09bce388f595b15bb5fb6"),
"floorId" : ObjectId("59a09abe388f595b15bb5fa3"),
"name" : "bathroom"
},
{
"_id" : ObjectId("59a09bce388f595b15bb5fc6"),
"floorId" : ObjectId("59a09abe388f595b15bb5fa3"),
"name" : "living room"
}
]
},
{
"_id" : ObjectId("59a09abe388f595b15bb5fa2"),
"buildingId" : ObjectId("59a09abe388f595b15bb5fa6"),
"name" : "downstairs",
"rooms" : [ ]
}
]
}
As you see I would like to lookup all the references to get the building structure with it's floors and rooms.
How can I achieve that?