I have a nested embedded document which looks something like this. Each post has n-comments and each comment has a user detail with name and email id.
I want to project just the name of the commented user into the list
{
"PostId":"Post001",
"Comments":[
{"_id": "001",
"CommentedBy":{
"_id":"User001",
"Name":"UserName001",
"email":"[email protected]"
}
},
{"_id": "002",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"[email protected]"
}
},
{"_id": "003",
"CommentedBy":{
"_id":"User003",
"Name":"UserName003",
"email":"[email protected]"
}
}
]
}
And I want to transform into something that looks like this, by using mongodb's aggregation pipeline.
{
"PostId":"Post001"
"Comments":[
{"_id": "001",
"CommentedBy":"UserName001",
},
{"_id": "002",
"CommentedBy": "UserName002"
},
{"_id": "003",
"CommentedBy": "UserName003"
}
]
}
Using mongo's projection query provides a list of CommentedBy with all the names in it. How can I achieve this using mongo's aggregate query. Is there a way to do it without using $unwind.
Query I tried and the result I got.
db.getCollection('post').aggregate([
{$project:{"Comments.CommentedBy":"$Comments.CommentedBy.Name"}}
])
{
"_id" : ObjectId("5b98b4cc3bb8c65aeacabd78"),
"Comments" : [
{
"CommentedBy" : [
"UserName001",
"UserName002",
"UserName003"
]
},
{
"CommentedBy" : [
"UserName001",
"UserName002",
"UserName003"
]
},
{
"CommentedBy" : [
"UserName001",
"UserName002",
"UserName003"
]
}
]
}