Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB聚合,查找文档中不同值的数量';阵列_Mongodb_Pymongo - Fatal编程技术网

MongoDB聚合,查找文档中不同值的数量';阵列

MongoDB聚合,查找文档中不同值的数量';阵列,mongodb,pymongo,Mongodb,Pymongo,通过阅读,我发现您可以获得文档数组中的元素数。例如,给定以下文档: { "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] } { "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] } { "_id" : 3, "item" : "XYZ1", "descrip

通过阅读,我发现您可以获得文档数组中的元素数。例如,给定以下文档:

{ "_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" }}}])
我们将获得每个文档的
颜色
数组中的元素数:

{ "_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
 ])

更好的方法是简单地:

如果您希望“在每个文档中都是不同的”,那么您应该:

db.inventory.aggregate([
  { "$group": {
    "_id": null,
    "totalColors": {
      "$sum": {
        "$size": { "$setUnion": [ [], "$colors" ] }
      }
    }
  }}
])
Where接受像
[“紫色”、“蓝色”、“紫色”]
这样的值,并将其作为带有“不同项”的“集合”放入
[“紫色”、“蓝色”]

如果您确实想要“跨文档区分”,那么不要将“区分”累积到单个文档中。这会导致性能问题,无法扩展到大型数据集,可能会突破16MB BSON限制。而是通过按键自然累积:

db.inventory.aggregate([
  { "$unwind": "$colors" },
  { "$group": { "_id": "$colors" } },
  { "$group": { "_id": null, "totalColors": { "$sum": 1 } } }
])
其中,您之所以使用,是因为您希望将数组中的“不同”值与其他文档结合使用。通常应避免,除非在的“分组键”
\u id
中访问数组中包含的值。如果不是,最好使用其他操作符来处理数组,因为
$unwind
会为每个数组元素创建整个文档的“副本”

当然,简单地使用here也没有什么错,它将“以数组的形式”返回“不同的”值,您可以在代码中对其进行测试:

var totalSize = db.inventory.distinct("colors").length;
对于您所要求的简单操作,对于简单的“不同元素计数”,这将是整体最快的方法。当然,限制仍然存在,即作为有效负载,结果不能超过16MB BSON限制。在这里,您可以改为使用
.aggregate()

var totalSize = db.inventory.distinct("colors").length;