我可以使用聚合框架轻松地将子文档的所有字段作为顶级文档中的字段返回吗? [英] Can I easily return all of the fields of a subdocument as fields in the top level document using the aggregation framework?
本文介绍了我可以使用聚合框架轻松地将子文档的所有字段作为顶级文档中的字段返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似于以下内容的文档,我想从中返回当前顶级字段的子字段作为结果数组的每个文档中的顶级字段:
I have a document similar to the following, from which I want to return the sub-fields of the current top level field as the top level fields in every document of the results array:
{
field1: {
subfield1: {},
subfield2: [],
subfield3: 44,
subfield5: xyz
},
field2: {
othercontent: {}
}
}
我希望聚合查询的结果返回以下内容(field1
的内容作为顶级文档):
I want the results of my aggregation query to return the following (the contents of field1
as the top level document):
{
subfield1: {},
subfield2: [],
subfield3: 44,
subfield5: xyz
}
可以使用$project
和聚合框架完成此操作,而无需定义要返回为顶级字段的每个子字段吗?
Can this be done with $project
and the aggregation framework without defining every sub fields to return as a top level field?
推荐答案
You can use $replaceRoot aggregation operator since 3.4:
db.getCollection('sample').aggregate([
{
$replaceRoot: {newRoot: "$field1"}
}
])
按预期提供输出:
{
"subfield" : {},
"subfield2" : [],
"subfield3" : 44,
"subfield5" : "xyz"
}
这篇关于我可以使用聚合框架轻松地将子文档的所有字段作为顶级文档中的字段返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文