2016-02-26 90 views
1

我只是想通过$project管道添加一个新的领域,让其他属性进行进一步的处理漏网之鱼,我知道,你可以这样做:

db.people.aggregate([ 
    {$project: {name: 1, address: 1, birth_month: {$month: "$birthdate"}}} 
]) 

但随着越来越多的复杂的文档,我有在$project中编写20 ++字段名称非常困难。我可以再补充通过汇聚管道中的场,使得我没有一个有规定的其他领域的一个办法,像

db.people.aggregate([ 
    {$appendField: {birth_month: {$month: "$birthdate"}}} 
]) 
+0

在这种情况下,不添加超过20场,而投入项目,你不想那场{$项目:{名称:0}}在这种情况下,将选择除名字外的所有字段。 –

+0

我认为你误解了,我想保留原始文档的所有字段完好无损,但是增加了一个字段(birth_month) – DennyHiu

+0

....并且不必在$ project中写下其他字段名称 – DennyHiu

回答

1

最后,我能解决这个问题。刚刚阅读这里的旧帖子(MongoDB $project: Retain previous pipeline fields,感谢@Johnny HK)。这里是我的解决方案(蒙戈2.6或更高版本):

db.people.aggregate([ 
    {$project: {doc: "$$ROOT", birth_month: {$month: "$birthdate"}}} 
    {$group: {_id: "$doc.gender"} } <-- here you can use fields of the original doc via $doc 
]) 
相关问题