2017-07-23 94 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()的是哪个地方。

相关问题