Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use $project to return a field as the top level document in a mongo aggregation query?

I have a document similar to the following, where I want to return a field of the current top level documents as the top level document itself in the results array:

{    field1:{contents:{}}   field2:{othercontent:{}} } 

I want the results of my aggregation query to return the following

{   contents:{} } 

Can this be done with $project and the aggregation framework?

like image 206
Gary Sharpe Avatar asked Oct 17 '13 18:10

Gary Sharpe


1 Answers

Yes, you can use $project to do that. You just have to tell it to retrieve the nested contents object using dot notation:

db.items.aggregate( {$project: {contents:'$field1.contents'}} ); 

Additionally, if you want to to hide the _id field from the output, you can specify _id: 0 in the $project parameters:

db.items.aggregate( {$project: {contents:'$field1.contents', _id:0}} ); 
like image 85
Cristian Lupascu Avatar answered Sep 30 '22 02:09

Cristian Lupascu