Which scenario best suggests using embedding documents instead of referencing (joins) in MongoDB?
Think about data locality and update frequency.
Embedding is best when related data is accessed together and changes rarely, improving read performance by avoiding joins.
Given two collections, orders and customers, what will be the output of this aggregation?
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}
}db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}
}
])Recall what $lookup does in aggregation pipelines.
$lookup performs a left outer join, adding an array of matching documents from the 'from' collection to each input document.
Which option contains a syntax error in embedding a subdocument inside a MongoDB insert?
db.products.insertOne({
name: "Laptop",
specs: {
cpu: "Intel i7",
ram: "16GB",
storage: "512GB SSD"
}
})Check the use of brackets for subdocuments.
Option B uses square brackets [] instead of curly braces {} for the embedded document, which is invalid syntax.
You have a blog application where each post has many comments. Which data modeling choice optimizes read performance when displaying posts with comments?
Consider how many queries are needed to read posts with comments.
Embedding comments inside posts reduces the number of queries needed to fetch all related data, improving read speed.
Given collections users and orders, this aggregation returns empty arrays in the orders field. Why?
db.users.aggregate([
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}
}
])Check data types of join fields.
If the join fields have different data types (ObjectId vs string), the join will not match any documents, resulting in empty arrays.