3

Here is my pymongo call

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()

For some reason resulting list is empty, while in Robomongo I get nonempty output.

Is formatting incorrect?

The exact Robomongo query is

db.some_details.aggregate([{$group: {_id: '$mvid', count: {$sum: 1}}}])

UPDATE The output looks like

{
    "result" : [ 
        {
            "_id" : "4f973d56a64facfaa7c3r4rf262ad5be695eef329aff7ab4610ddedfb8137427",
            "count" : 84.0000000000000000
        }, 
        {
            "_id" : "a134106e1a1551d296fu777cedc933e7df2d0a9bc5f41de047aba3ee29bace78",
            "count" : 106.0000000000000000
        }, 

    ],
    "ok" : 1.0000000000000000
}
1
  • what is the result of db in Robomongo?
    – styvane
    Jun 27, 2015 at 1:53

1 Answer 1

5

You are again adding db to collection otherwise code seems to be OK to me.

Here is modified version of your code :

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()
2
  • Thank you, Abhijeet. Dropping db did not help. Simpler queries such as find work without db, but aggregate is different. Plus official pymongo tutorial mentions db (api.mongodb.org/python/current/examples/…). I guess I going to try to dump query output to json file and then read it into python. Jun 27, 2015 at 14:06
  • Apologies, Abhijeet! Actually removing db helped. The returning object is some sort of collection of dictionaries. Casting it to list does not work, but one can iterate through this collection. I guess official pymongo tutorial is not very accurate. Jun 29, 2015 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.