MongoDB - Query to display childname with his parent name
Lets say we have following data in our person collection.
db.person.insertMany([
{ _id: 1, name: "Tushar Mane", parentId: 0 },
{ _id: 2, name: "Nitin Mane", parentId: 1 },
{ _id: 3, name: "Suraj Kohli", parentId: 0 },
{ _id: 4, name: "Daksha Kohli", parentId: 3 },
{ _id: 5, name: "Sushil Mane", parentId: 1 }
]);
{ "acknowledged" : true, "insertedIds" : [ 1, 2, 3, 4, 5 ] }
db.person.find({})
{ "_id" : 1, "name" : "Tushar Mane", "parentId" : 0 }
{ "_id" : 2, "name" : "Nitin Mane", "parentId" : 1 }
{ "_id" : 3, "name" : "Suraj Kohli", "parentId" : 0 }
{ "_id" : 4, "name" : "Daksha Kohli", "parentId" : 3 }
{ "_id" : 5, "name" : "Sushil Mane", "parentId" : 1 }
Write a query to display output as shown below.
childId | childName | parentId | parentName
db.person.aggregate([
{
$lookup: {
from: "person",
localField: "parentId",
foreignField: "_id",
as: "parent"
}
},
{
$unwind: {
path: "$parent",
//preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id:0,
childId: "$_id",
childName: "$name",
parentId: "$parent._id",
parentName: "$parent.name"
}
}
]);
