Here is the code in mongodb playground.
I have a query that looks like below:
db.posts.aggregate({
$lookup: {
from: "users",
let: {comments: "$comments"},
pipeline: [
{$match: {$expr: {$in: ["$_id", "$$comments.userId"]} }},
{"$addFields":{"text": "$$comments.text"}}
],
as: "comments"
}
})
The problem with this query is that the text value I get is is an array containing the texts from all comments. If I try to filter by userId, I get another problem. If a user has commented more than once the text value will be an array containing all of their comments.
How can I get the looked up user and their comment as in one object?
EDIT
I expect a result that looks like below:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"id": "1",
"comments": [
{
"_id": "u1",
"name": "James",
"username": "jamo",
"text": "Hi there, who are you?"
},
{
"_id": "u1",
"name": "James",
"username": "jamo",
"text": "Hi! Are you still there?"
}
],
}
]