mongo 中的聚合查询有效,Pymongo 中无效 [英] Aggregate query in mongo works, does not in Pymongo

查看:52
本文介绍了mongo 中的聚合查询有效,Pymongo 中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题.我尝试通过COL"数组之外的 LOC 标识符查询此文档以获取金额和分组的总和.

I encountered a problem. I try to query this document to obtain the sum the amount and group by the LOC identifier that is outside the "COL" array.

{
"_id" : ObjectId("57506d74c469888f0d631be6"),
"LOC" : "User001",
"COL" : [ 
    {
        "date" : "25/03/2016",
        "number" : "Folio009",
        "amount" : 100
    }, 
    {
        "date" : "25/04/2016",
        "number" : "Folio010",
        "amount" : 100
    }

]}

此命令在 mongo 中有效,但我无法使用 Pymongo 包使其在 Python 中运行:

This command works in mongo but I cannot make it work in Python with the Pymongo package:

db.perfiles.aggregate({"$unwind": "$COL"},
{ "$group": { _id: "$LOC", "sum" : {"$sum" : "$COL.amount" }}})

Pymongo(不工作)

from pymongo import MongoClient

client = MongoClient()

db = client['temporal']

docs = db.perfiles


pipeline = [{"$unwind": "$COL"},
     {"$group": {"_id": "$LOC", "count": {"$sum": "$COL.amount"}}}
          ]

list(db.docs.aggregate(pipeline))

有什么建议可以在 Pymongo 中查询相同的查询?谢谢!

Any suggestion to query this same query but in Pymongo? Thanks!

推荐答案

我假设您在 Python 中有一个到 MongoDB 的有效连接.
以下代码片段将在 result.

I assume you have a valid connection to MongoDB in Python.
The following code snippet will return a MongoDB cursor in result.

pipeline = [
    {"$unwind": "$COL"},
    {"$group": {"_id": "$LOC", "sum": {"$sum": "$COL.amount"}}}
]

cursor = collection.aggregate(pipeline)

现在您可以将cursor 转换为列表

Now you can convert cursor to list

result = list(cursor)

如果您打印结果的值,您将获得与 Shell 查询完全相同的结果.

and if you print result's value, you'll get exactly the same result as in your Shell query.

[{u'sum': 200.0, u'_id': u'User001'}]

更新:

我看到您在 python 代码中将 aggregate 函数调用为 db.docs.aggregate(pipeline).您需要将其称为 docs.aggregate... 而无需 db.请参阅上面的示例.

I see that you are calling the aggregate function in python code as db.docs.aggregate(pipeline). You need to call it as docs.aggregate... without db. See example above.

这篇关于mongo 中的聚合查询有效,Pymongo 中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆