閱讀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 }