2016-05-05 124 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}}} 
])