Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k 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"}}}

          ]

list(db.docs.aggregate(pipeline))

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

1 Answer

0 votes
by (107k points)
edited by

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

Also, have a look at this professional Full Stack Developer Training, designed to enhance your skills in the field.

Related questions

0 votes
1 answer
0 votes
3 answers
asked Sep 4, 2019 in SQL by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...