2016-05-05 123 views
1

事实上,我没有找到有关此文档的信息,这意味着我可能以错误的方式处理这个问题。也许你可以帮忙。查找文档并合并子文档

我想找到斯皮尔伯格所有的电影。 简单:

Movies.find({credits.who: "Spielberg"}).exec(function....) 

它返回:

{ 
    credits: [{ 
     role: "director", 
     who: "Spielberg" 
    }, { 
     role: "writer", 
     who: "Spielberg" 
    }], 
    title : "The flying unicorn", 
    summary: "a unicorn flies" 
} 
{ 
    credits: [{ 
     role: "director", 
     who: "someone else" 
    }, { 
     role: "writer", 
     who: "Spielberg" 
    }], 
    title : "The falling unicorn", 
    summary: "a unicorn plumits to its death" 
} 

但我想要的结果也有汇总信息的新条目:

{role: "director", #ofCredits: 1} 
{role: "writer", #ofCredits: 2} 

我怎样才能做到这一点?

回答

1

测试工作完全正常:

db.getCollection('test').aggregate([ 
{$match:{"credits.who":"Spielberg"}}, 
{$unwind:"$credits"}, 
{$project:{"credits.role":1,"credits.who":1}}, 
{"$group":{"_id":{"role":"$credits.role"},"#ofCredits":{"$sum": 1}}} 
])