阅读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 }