我可以使用 $project 返回一个字段作为 mongo 聚合查询中的顶级文档吗? [英] 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:{}
}
这可以通过 $project 和聚合框架来完成吗?
Can this be done with $project and the aggregation framework?
推荐答案
是的,您可以使用 $project
来做到这一点.你只需要告诉它使用 点符号:
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'}} );
另外,如果你想在输出中隐藏_id
字段,你可以在$project
参数中指定_id:0
:
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}} );
这篇关于我可以使用 $project 返回一个字段作为 mongo 聚合查询中的顶级文档吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!