阅读文档,我看到您可以获得文档数组中的元素数量。例如给出以下文件:
{ "_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
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句