0

I have following query in my database

query = u'collection.aggregate([{ "$match": { "code": { "$in": {__sensors__}} } },{"$project" : {"_id" : 0}},{"$group" : {"_id": "$code", "data": {"$last": "$$ROOT"}}}])'

And I have following arguments, Now I want to pass that argument in the above query.

args = {"__sensors__": ["GP0", "GP1", "GP5", "GP6"]}

I'm trying following but it is giving me an error.

query.format(**args)

above statement giving me this error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-44-7db1aba33ea5> in <module>()
----> 1 a.query.format({"__sensors__": []})

KeyError: u' "$match"'

Can anyone give me the solution for the above problem?

1 Answer 1

1

Your problem is because of the { and }. When you use them in format python thinks that maybe that is a variable. So to fix that you need to make it double. Like below:

query = u'collection.aggregate([{{ "$match": {{ "code": {{ "$in": {__sensors__}}} }} }},{{"$project" : {{"_id" : 0}}}},{{"$group" : {{"_id": "$code", "data": {{"$last": "$$ROOT"}}}}}}])'

As you see I didn't double the {__sensors__}. Because your're going to replace it in the query.format(**args) line.

The final result would be like this:

'collection.aggregate([{ "$match": { "code": { "$in": [\'GP0\', \'GP1\', \'GP5\', \'GP6\']} } },{"$project" : {"_id" : 0}},{"$group" : {"_id": "$code", "data": {"$last": "$$ROOT"}}}])'
Sign up to request clarification or add additional context in comments.

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.