0 votes
1 view
in Web Technology by (32.3k points)

I want to query the following document so that I can get the total of the amount and group it by the LOC field:


"_id" : ObjectId("57506d74c469888f0d631be6"),

"LOC" : "User001",

"COL" : [ 


        "date" : "25/03/2016",

        "number" : "Folio009",

        "amount" : 100



        "date" : "25/04/2016",

        "number" : "Folio010",

        "amount" : 100


] }

The following code is working in the mongo shell but the same thing is not working in Python with the Pymongo package:

Mongo query (working)

db.perfiles.aggregate({"$unwind": "$COL"},

{ "$group": { _id: "$LOC", "sum" : {"$sum" : "$COL.amount" }}})

Pymongo (not working)

from pymongo import MongoClient

client = MongoClient()

db = client['temporal']

docs = db.perfiles

pipeline = [{"$unwind": "$COL"},

     {"$group": {"_id": "$LOC", "count": {"$sum": "$COL.amount"}}}



Can somebody guide me on why it is not working in Python with the Pymongo?

1 Answer

0 votes
by (71.3k points)

By your code, I can notice you are calling db.docs.aggregate(pipeline) in python. But you should not call it with db, just call it as docs.aggregate. Refer the following code:

pipeline = [

    {"$unwind": "$COL"},

    {"$group": {"_id": "$LOC", "sum": {"$sum": "$COL.amount"}}}


cursor = collection.aggregate(pipeline)

After that just convert the cursor to the list:

result = list(cursor)

If you are a beginner and want to know more about MongoDB then do check out the mongodb tutorial


Related questions

0 votes
1 answer
0 votes
2 answers
asked Sep 4, 2019 in SQL by Sammy (47.8k points)
0 votes
1 answer
asked Feb 9 in Web Technology by ashely (32.3k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !