pymongo和聚合的输出

时间:2015-06-26 21:19:41

标签: output aggregate pymongo

这是我的pymongo电话

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['somedb']
collection = db.some_details
pipe = [{'$group': {'_id': '$mvid', 'count': {'$sum': 1}}}]
TestOutput = db.collection.aggregate(pipeline=pipe)
print(list(TestOutput))
client.close()

由于某种原因,结果列表为空,而在Robomongo中我得到非空输出。

格式不正确吗?

确切的Robomongo查询是

db.some_details.aggregate([{$group: {_id: '$mvid', count: {$sum: 1}}}])

更新 输出看起来像

{
    "result" : [ 
        {
            "_id" : "4f973d56a64facfaa7c3r4rf262ad5be695eef329aff7ab4610ddedfb8137427",
            "count" : 84.0000000000000000
        }, 
        {
            "_id" : "a134106e1a1551d296fu777cedc933e7df2d0a9bc5f41de047aba3ee29bace78",
            "count" : 106.0000000000000000
        }, 

    ],
    "ok" : 1.0000000000000000
}

1 个答案:

答案 0 :(得分:3)

您再次将db添加到collection,否则代码对我来说似乎没问题。

以下是您的代码的修改版本:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['somedb']
collection = db.some_details
pipe = [{'$group': {'_id': '$mvid', 'count': {'$sum': 1}}}]
# Notice the below line
TestOutput = collection.aggregate(pipeline=pipe)
print(list(TestOutput))
client.close()