Reputation: 890
This is a document in the collection BlogPosts
:
{
_id: ObjectId("..."),
post_title: "Hello World!",
post_body: "",
comments: [
{ user_id: ObjectId("123"), body: "nice post!" },
{ user_id: ObjectId("456"), body: "awesome!" },
]
}
I would like to display comments with the user's first name, which is found in the referenced document in the Users
collection:
{
_id: ObjectId("123"),
first_name: "Marion",
last_name: "Smith",
email_address: "[email protected]",
password: "..."
}
Is there a way to retrieve the BlogPosts
document while including first_name
from this referenced data?
For example, I'm looking for an output like this (each comment has a first name):
{
_id: ObjectId("..."),
post_title: "Hello World!",
post_body: "",
comments: [
{ user_id: ObjectId("..."), first_name: "Marion", body: "nice post!" },
{ user_id: ObjectId("..."), first_name: "Margaret", body: "awesome!" },
]
}
I'm using Mongoose.
Upvotes: 1
Views: 603
Reputation: 46461
You can use below aggregation
db.collection.aggregate([
{ "$unwind": "$comments" },
{ "$lookup": {
"from": "users",
"let": { "userId": "$comments.user_id" },
"pipeline": [{ "$match": { "$expr": { "$eq": ["$$userId", "$_id"] } } }],
"as": "user"
}},
{ "$addFields": {
"comments.first_name": { "$arrayElemAt": ["$user.first_name", 0] }
}},
{ "$group": {
"_id": "$_id",
"comments": { "$push": "$comments" },
"post_title": { "$first": "$post_title" },
"post_body": { "$first": "$post_body" }
}}
])
Upvotes: 2