Outcome of $project in an aggregation

Hello,

I’m trying to get the values of the fields contained in a nested document.

My collection is called posts. The key of the nested document is “comments_full”. The keys of the values I want to project are “commenter_id”, “commenter_url” and “commenter_name”. Thus my query is:

db.posts.aggregate([{$project: {
   "comments_full.commenter_id": 1, 
   "comments_full.commenter_url": 1, 
   "comments_full.commenter_name": 1, 
   "_id": 0
}}])

I get results like the following one:

{ "comments_full" : [ {
   "commenter_id" : "xxxxxxxxxxxxxx",
   "commenter_url" : "xxxxxxxxxxxxxxxxxx", 
   "commenter_name" : "zzzzzzzzzzzz" 
  },
  { 
   "commenter_id" : "xxxxxxxxxxxxxx", 
   "commenter_url" : "xxxxxxxxxxxxxxxxxx", 
   "commenter_name" : "zzzzzzzzzzzz" 
  } 
 ] 
}

How can I get a result document like the following one, without the “comments_full” key?

{
  "commenter_id" : "xxxxxxxxxxxxxx", 
  "commenter_url" : "xxxxxxxxxxxxxxxxxx", 
  "commenter_name" : "zzzzzzzzzzzz" 
}

Thanks in advance for your help!

Best,

Miguel

Hi @Miguel_Marti_Menzel, welcome to the community.
Have you tried using the $unwind stage already?
If not, I would recommend using it because, it:

Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

Thanks for the hint, Sourabh!
I think the $unwind stage is not explained in the M001 course. I will investigate it in the documentation then.

Best regards,

Miguel

1 Like

Hi @Miguel_Marti_Menzel, M001 is a MongoDB-basics course, which is not supposed to go in-depth with every aggregation operator.
If you want to learn more about the aggregation framework, I would highly recommend this M121: MongoDB Aggregation Framework course.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

Thanks, Sourabh. I will attend the M121 course for sure.

Best regards,

Miguel

1 Like