Search This Blog

2024/04/24

MongoDb Interview Question:Join multiple collections

Assume we have three collections (authors, authorInfo, and userRole) with the
following data:

db.authors.insertMany([
{
"_id" : ObjectId("5d0127aaee66e13d34c7c389"),
"address" : "32 Makram Ebeid Street",
"isActive" : true,
"authorId" : "121"
}
])

db.authorInfo.insertMany([
{
"_id" : ObjectId("5d0f726bac65f929d0fa98b2"),
"authorId" : "121",
"description" : "A description"
}
])


db.userRole.insertMany([
{
"_id" : ObjectId("5d012a08ee66e13d34c7c38f"),
"userId" : "121",
"role" : "manager"
}
])

How can we join the authors from all three collections

Answers:

db.authors.aggregate( [
{
$lookup:
{
from: "authorInfo",
localField: "authorId",
foreignField: "authorId",
as: "authorInfo"
}
},{
$unwind: "$authorInfo"
},
{
$lookup:
{
from: "userRole",
localField: "authorId",
foreignField: "userId",
as: "userRole"
}
},
{
$unwind:"$userRole"
},{
$project:{
_id:1,
address:1,
isActive:1,
authorId:1,
description:"$authorInfo.description",
role:"$userRole.role"
}
}
])

Note:
$lookup does not work in case of sharded collection.

No comments:

Post a Comment