我可以使用$ project将字段作为mongo聚合查询中的顶级文档返回吗?

Gar*_*rpe 14 mongodb mongodb-query

我有一个类似于以下的文档,我想在结果数组中返回当前顶级文档的字段作为顶级文档本身:

{ 
  field1:{contents:{}}
  field2:{othercontent:{}}
}
Run Code Online (Sandbox Code Playgroud)

我希望我的聚合查询的结果返回以下内容

{
  contents:{}
}
Run Code Online (Sandbox Code Playgroud)

这可以用$ project和聚合框架完成吗?

Cri*_*scu 18

是的,你可以用它$project来做到这一点.您只需要告诉它contents使用点表示法检索嵌套对象:

db.items.aggregate( {$project: {contents:'$field1.contents'}} );
Run Code Online (Sandbox Code Playgroud)

此外,如果_id要从输出中隐藏字段,可以_id: 0$project参数中指定:

db.items.aggregate( {$project: {contents:'$field1.contents', _id:0}} );
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 11

  • 从 开始Mongo 3.4$replaceRoot聚合运算符可用于将文档替换为另一个文档(在我们的示例中为子文档):

    // { field1: { content: { a: 1, b: 2 } }, field2: { othercontent: {} } }
    // { field1: { content: { c: 1, d: 2 } }, field2: { othercontent: {} } }
    db.collection.aggregate({ $replaceRoot: { newRoot: "$field1" } })
    // { content: { a: 1, b: 2 } }
    // { content: { c: 1, d: 2 } }
    
    Run Code Online (Sandbox Code Playgroud)
  • 开始Mongo 4.2$replaceWith也可以使用运算符:

    db.collection.aggregate({ $replaceWith: "$field1" })
    
    Run Code Online (Sandbox Code Playgroud)