mongo中的聚合查询有效,不在Pymongo中

时间:2016-06-30 21:24:59

标签: python mongodb pymongo

我遇到了一个问题。我尝试查询此文档,以获取“COL”数组之外的LOC标识符的数量和组的总和。

{
"_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中工作:

Mongo查询(正在工作)

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中查询同一个查询的任何建议?谢谢!

3 个答案:

答案 0 :(得分:6)

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

中返回MongoDB游标
pipeline = [
    {"$unwind": "$COL"},
    {"$group": {"_id": "$LOC", "sum": {"$sum": "$COL.amount"}}}
]

cursor = collection.aggregate(pipeline)

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

result = list(cursor)

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

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

<强>更新

我看到你在python代码中调用aggregate函数db.docs.aggregate(pipeline)。 您需要在没有docs.aggregate...的情况下将其称为db。见上面的例子。

答案 1 :(得分:1)

MongoDB Enterprise > db.test.aggregate([{$match:{name:'prasad'}},{$group : {_id : "$name", age : {$min : "$age"}}}]);
{ "_id" : "prasad", "age" : "20" }
MongoDB Enterprise > db.test.find()
{ "_id" : ObjectId("5890543bce1477899c6f05e8"), "name" : "prasad", "age" : "22" }
{ "_id" : ObjectId("5890543fce1477899c6f05e9"), "name" : "prasad", "age" : "21" }
{ "_id" : ObjectId("58905443ce1477899c6f05ea"), "name" : "prasad", "age" : "20" }
{ "_id" : ObjectId("5890544bce1477899c6f05eb"), "name" : "durga", "age" : "20" }
{ "_id" : ObjectId("58905451ce1477899c6f05ec"), "name" : "durga", "age" : "21" }
{ "_id" : ObjectId("58905454ce1477899c6f05ed"), "name" : "durga", "age" : "22" }
MongoDB Enterprise >    


############code


import pymongo
from pymongo import MongoClient
client=MongoClient("localhost:27017")
db=client.prasad      #####prasad is dbname, test is collection name
nameVar='prasad'
aggregation_string=[{"$match":{"name":nameVar}},{"$group" : {"_id" : "$name", "age" : {"$min" : "$age"}}}]
x=db.test.aggregate(aggregation_string)
print x
for r in x:
        min_age=r.items()[0]
        print(min_age[1])      #######output:      20

答案 2 :(得分:0)

you are in a right track but add one more statement it will be fine.
    from pymongo import MongoClient

    client = MongoClient()

    db = client['temporal']

    docs = db.perfiles


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

    result = list(db.docs.aggregate(pipeline))

    for i in result:

        sum += i['sum']

    print(sum)