Pymongo和聚合操作的输出结果

3

这是我的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
}

在Robomongo中,db的结果是什么? - styvane
1个回答

5
您再次将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()

谢谢,Abhijeet。删除 db 没有帮助。像 find 这样的简单查询可以在没有 db 的情况下工作,但是 aggregate 不同。此外,官方的 pymongo 教程提到了 db(http://api.mongodb.org/python/current/examples/aggregation.html?highlight=aggregate)。我想我会尝试将查询输出转储到 json 文件中,然后再读入到 python 中。 - user1700890
抱歉,Abhijeet!实际上移除 db 有所帮助。返回的对象是一些字典的集合。强制转换为 list 不起作用,但可以通过此集合进行迭代。我想官方的 pymongo 教程并不是很准确。 - user1700890

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接