Lets consider the example provided here
For the same of this discussion, let us assume that orders <-> items, is a many to one relationship. ie for every order, there is only one item what would match in a lookup
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }
])
db.items.insert([
{ "_id" : 1, "item" : "almonds", description: "almond clusters", "instock" : 120 },
{ "_id" : 2, "item" : "bread", description: "raisin and nut bread", "instock" : 80 },
{ "_id" : 3, "item" : "pecans", description: "candied pecans", "instock" : 60 }
])
The $replaceRoot
aggregation
db.orders.aggregate([
{
$lookup: {
from: "items",
localField: "item", // field in the orders collection
foreignField: "item", // field in the items collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
])
The $unwind
aggregation
db.orders.aggregate([
{
$lookup: {
from: "items",
localField: "item", // field in the orders collection
foreignField: "item", // field in the items collection
as: "fromItems"
}
},
{
$unwind: "$fromItems"
}
])
I understand that $replaceRoot
(with $mergeObject
), embeds the fields directly (or merges) into the document, while $unwind
creates a sub-document
Q1: Assuming I am fine with either document schemas, I would like to know which one has better performance in terms of RAM used, execution duration.
Q2: How can I measure/view these performance metrics? db.orders.aggregate(…).explain() does not provide the info I need