2

I am using below query to get data from the collection in mongodb

db.testcoll.aggregate([​
  { $unwind :'$data'},​
  { $match : {'type': 'data1', "my_id" : "44ef", 'data.time': { $gte : "2018-07-07 00:00:30" , $lte : "2018-07-08 00:57:30"} }},​
  { $project : { _id:0, my_id: '$my_id', time : '$data.time', value : '$data.value'} }​
])

Running the above query in MongoDb, I get appropriate results. Now I am writing a small python script where I need to run the same query.

query = ([​
  { '$unwind' :'$data'},​
  { '$match' : {'type': 'data1', "my_id" : "44ef", 'data.time': { '$gte' : "2018-07-07 00:00:30" , '$lte' : "2018-07-08 00:57:30"} }},​
  { '$project' : { '_id':0, 'my_id': '$my_id', 'time' : '$data.time', 'value' : '$data.value'} }​
])

document = testcoll.find(query)
for i in document:
    print(i)

It shows document values as None in debugger and thus throws error:

TypeError: 'NoneType' object is not iterable

How can I run the query in python. Thanks

1
  • python driver should have documentation on mongodb site, with examples and everything. Have you checked that out? Commented Sep 12, 2018 at 11:36

2 Answers 2

2

You can use the same query of mongo in python to run

query = [
  { '$unwind' :'$data'},​
  { '$match' : {'type': 'data1', "my_id" : "44ef", 'data.time': { '$gte' : "2018-07-07 00:00:30" , '$lte' : "2018-07-08 00:57:30"} }},​
  { '$project' : { '_id':0, 'my_id': '$my_id', 'time' : '$data.time', 'value' : '$data.value'} }​
]
document = testcoll.aggregate(query)
for i in document:
    print(i)
Sign up to request clarification or add additional context in comments.

Comments

1

As the documentation states, you need to use the aggregate function.

query = ([​
  { '$unwind' :'$data'},​
  { '$match' : {'type': 'data1', "my_id" : "44ef", 'data.time': { '$gte' : "2018-07-07 00:00:30" , '$lte' : "2018-07-08 00:57:30"} }},​
  { '$project' : { '_id':0, 'my_id': '$my_id', 'time' : '$data.time', 'value' : '$data.value'} }​
])

document = testcoll.aggregate(query)
for i in document:
    print(i)

Also, seems you are new to pymongo but something to look into. PyMongo is great but every interaction you make with it is blocking. Consider using Motor it allows for async/await (or even Flask if that's what you use) Almost all the same functions work with it but they are non blocking.

With motor it would just become:

document = await testcoll.aggregate(query)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.