阅读the docs ,我看到你可以获取文档数组中的元素数量。例如给出以下文档:
{ "_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 }
最佳答案
您可以使用以下查询来获取所有文档中所有颜色的计数:
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
])
关于MongoDB 聚合,查找文档数组中不同值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45269591/