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

后端 未结 2 1899
既然无缘
既然无缘 2020-12-29 06:17

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:

2条回答
  •  忘掉有多难
    2020-12-29 07:06

    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}} );
    

提交回复
热议问题