[英]Pass parameter in string mongo query in python
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? 有人可以给我解决上述问题的方法吗?
Your problem is because of the {
and }
. 您的问题是因为
{
和}
。 When you use them in format
python thinks that maybe that is a variable. 当您以
format
使用它们时,python认为这可能是一个变量。 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__}
. 如您所见,我没有将
{__sensors__}
加倍。 Because your're going to replace it in the query.format(**args)
line. 因为您要在
query.format(**args)
行中替换它。
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"}}}])'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.