合并mongodb汇总结果

时间:2016-05-15 10:51:07

标签: mongodb

我有一个集合说user。每个文档的结构都是这样的

_id:String
status:Int32
account:{
    firstName:
    lastName:
    .. some other nested property
}
..some more property

我的最终目标是在fullName字段中生成一个新的嵌套字段account,该字段是两个名称字段的串联。我可以像这样运行aggregate查询

db.user.aggregate(
[
  { $project: { 'account.name': { $concat: [ "$account.firstName", "  ", "$account.lastName" ] } } }
])

如果我将$out与db name一起写,但我的现有数据会被替换。我如何实际合并,以便我的最终结构保持为

_id:String
status:Int32
account:{
    firstName:String
    lastName:String
    fullName:String
    .. some other nested property
}
..some more property

1 个答案:

答案 0 :(得分:1)

$project 管道中,您需要在embedded fields上使用点符号包含其他字段,如下所示:

db.user.aggregate([
    { 
        "$project": { 
            "status": 1,
            "field1": 1, // the other properties
            "field2": 1,
            "account.firstName": 1,
            "account.lastName": 1,
            "account.name": {"$concat":["$account.firstName", "  ", "$account.lastName"]}  
        } 
    },
    { "$out": "tempcollection" }
])
相关问题