2015-04-17 170 views
1

我有這樣的與文檔的集合:
MongoDB的聚合使用嵌套元素

"_id" : "15", 
    "name" : "empty", 
    "location" : "5th Ave", 
    "owner" : "machine", 
    "visitors" : [ 
     { 
      "type" : "M", 
      "color" : "blue", 
      "owner" : "Steve Cooper" 
     }, 
     { 
      "type" : "K", 
      "color" : "red", 
      "owner" : "Luis Martinez" 
     }, 
     // A lot more of these 
    ] 
} 

我想按visitors.owner找到其所有者擁有最參觀,我嘗試這樣做:

db.mycol.aggregate(
    [ 
      {$group: { 
       _id: {owner: "$visitors.owner"}, 
       visits: {$addToSet: "$visits"}, 
       count: {$sum: "comments"} 
      }}, 
      {$sort: {count: -1}}, 
      {$limit: 1} 
    ] 
) 

但我總是得到數= 0,而不是對應一個所有者訪問:/
請幫

回答

1

嘗試以下聚合管道:

db.mycol.aggregate([ 
    { 
     "$unwind": "$visitors" 
    }, 
    { 
     "$group": { 
      "_id": "$visitors.owner", 
      "count": { "$sum": 1} 
     } 
    }, 
    { 
     "$project": { 
      "_id": 0, 
      "owner": "$_id", 
      "visits": "$count" 
     }   
    } 
]); 

使用你在你的問題中提供的樣本文件,結果是:

/* 0 */ 
{ 
    "result" : [ 
     { 
      "owner" : "Luis Martinez", 
      "visits" : 1 
     }, 
     { 
      "owner" : "Steve Cooper", 
      "visits" : 1 
     } 
    ], 
    "ok" : 1 
} 
+1

它的工作!我添加了「{$ sort:{visits:-1}}」來讓所有者訪問次數最多。非常感謝 – Fourat

+0

@Fourat不用擔心:-) – chridam