2017-07-23 50 views
1

閱讀the docs,我看到您可以獲取文檔數組中的元素數量。例如,給定下列文件:MongoDB聚合,查找文檔數組中不同值的數量

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] } 
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] } 
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] } 

和下面的查詢:

db.inventory.aggregate([{$project: {item: 1, numberOfColors: { $size: "$colors" }}}]) 

我們將獲得在每個文檔的colors數組元素的個數:

{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 } 
{ "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 } 
{ "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 } 

我還沒有能夠弄清楚是否以及如何總結查詢中所有文檔中的所有顏色,即:

{ "totalColors": 4 } 

回答

2

您可以使用下面的查詢來獲取所有顏色的數量在所有文檔:

db.inventory.aggregate([ 
    { $unwind: '$colors' } , // expands nested array so we have one doc per each array value 
    { $group: {_id: null, allColors: {$addToSet: "$colors"} } } , // find all colors 
    { $project: { totalColors: {$size: "$allColors"}}} // find count of all colors 
]) 
1

無限好是是簡單地$sum$size

db.inventory.aggregate([ 
    { "$group": { "_id": null, "totalColors": { "$sum": { "$size": "$colors" } } } 
]) 

如果你想「在每個文件中不同「,那麼你會改爲:

db.inventory.aggregate([ 
    { "$group": { 
    "_id": null, 
    "totalColors": { 
     "$sum": { 
     "$size": { "$setUnion": [ [], "$colors" ] } 
     } 
    } 
    }} 
]) 

其中$setUnion取值爲["purple","blue","purple"],並將其作爲["purple","blue"]作爲具有「不同項目」的「集合」。

如果您確實想要「跨文檔」,那麼不要將「不同」累加到單個文檔中。這會導致性能問題,並且不會擴展到大數據集,並且可能會破壞16MB BSON限制。相反,通過關鍵自然積累:

db.inventory.aggregate([ 
    { "$unwind": "$colors" }, 
    { "$group": { "_id": "$colors" } }, 
    { "$group": { "_id": null, "totalColors": { "$sum": 1 } } } 
]) 

在那裏你只是因爲你想從數組「獨特」的價值觀與其他文件結合使用$unwind。除非在「分組鍵」_id$group中訪問陣列中包含的值,否則通常應避免使用$unwind。如果不是,則最好使用其他運算符來處理數組,因爲$unwind會爲每個數組元素創建一個「複製」整個文檔。

當然也有沒有錯,只是使用.distinct()在這裏,這將返回「獨特的」價值觀「爲陣」,爲此,你可以測試Array.length()在代碼:

var totalSize = db.inventory.distinct("colors").length; 

對於簡單的操作,您所要求的將是整個最快的方法,用於簡單的「不同元素的計數」。當然,限制仍然是結果不能超過作爲有效載荷的16MB BSON限制。代替.aggregate()的是哪個地方。

相關問題