Pymongo 统计所有文档中某个键的元素数量

0 投票
1 回答
994 浏览
提问于 2025-04-18 16:19

我想统计在MongoDB集合中某个键(somekey)出现的所有元素。

现在的代码是把somekey中的所有元素作为一个整体来看。

from pymongo import Connection

con = Connection()
db = con.database

collection = db.collection

from bson.code import Code
reducer = Code("""
  function(obj, prev){
  prev.count++;
  }
  """)

from bson.son import SON
results = collection.group(key={"somekey":1}, condition={}, initial={"count": 0}, reduce=reducer)
for doc in results:
  print doc

但是,我希望它能统计在任何包含somekey的文档中出现的所有元素。

这里有一个预期的例子。MongoDB中有以下这些文档。

{ "_id" : 1, “somekey" : [“AB", “CD"], "someotherkey" : "X" }
{ "_id" : 2, “somekey" : [“AB", “XY”], "someotherkey" : "Y" }

结果应该是一个按数量排序的列表,内容包括:

count: 2 "AB"
count: 1 "CD"
count: 1 "XY"

1 个回答

2

.group() 方法不能用于数组类型的元素,最接近的类似方法是 mapReduce,这样你可以更好地控制生成的键。

不过,其实这里更合适的方法是 聚合框架。这个方法是用原生代码实现的,不像其他方法那样需要使用 JavaScript 解释器。

从 MongoDB 的响应中,你不会得到一个“有序列表”,但你会得到一个类似的文档结果:

results = collection.aggregate([
    # Unwind the array
    { "$unwind": "somekey" },

    # Group the results and count
    { "$group": {
        "_id": "$somekey",
        "count": { "$sum": 1 }
    }}
])

结果会像这样:

{ "_id": "AB", "count": 2 }
{ "_id": "CD", "count": 1 }
{ "_id": "XY", "count": 1 }

撰写回答