2016-05-15 241 views
1

我有一个集合说user。每个文档的结构是这样的合并mongodb聚合结果

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

我的最终目标是在account场这是两个名称字段的连接来生成新的嵌套场fullName。如果我写$out与数据库名称一起,但我现有的数据会被替换,我可以运行aggregate这样的查询

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

。实际上,我怎么合并,这样我的最终结构仍然是

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

回答

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" } 
])