查找文档并聚合子文档

时间:2016-05-05 03:32:42

标签: mongodb mongoose

我没有找到关于这方面的文件这一事实意味着我可能以错误的方式接近这一点。也许你可以帮忙。

我正在努力寻找斯皮尔伯格被认可的所有电影。 容易:

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 个答案:

答案 0 :(得分: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}}}
])