I am developing a Flask REST API which will have three query parameters (HomeDevice, Key, UpdateDate), all passed as string. Now, I have to PyMongo query on Mongodb using these three inputs as filters.
typeof db.getCollection('collection_name').findOne().updatedate
>> Object
import json
from pymongo import MongoClient
import pandas as pd
client = MongoClient(<ServerAddress>,27017)
db = client.db_name
col = db.collection_name
updatedate="2020-01-13 06:43:47.500Z"
print(updatedate)
var = '{ "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
data = json.loads(var)
docs = pd.DataFrame(list(col.find(data)))
print(docs)
ISODate(updateDate) is causing JSONDecodeError, and after removing ISODate casting, query fetches empty frame.
JSONDecodeError Traceback (most recent call last)
<ipython-input-12-95360c676df4> in <module>
11
12 var = '{ "$and" : [{"homeDevice" : "Loader"} , {"keyed" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
---> 13 data = json.loads(var)
14 docs = pd.DataFrame(list(col.find(data)))
15 print(docs)
E:\Analytics\Installations\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
346 parse_int is None and parse_float is None and
347 parse_constant is None and object_pairs_hook is None and not kw):
--> 348 return _default_decoder.decode(s)
349 if cls is None:
350 cls = JSONDecoder
E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):
E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 1 column 81 (char 80)
Running this query directly in monogodb (Robo3T) returns data. I need a way to create query dynamically and apply ISODate on updatedate key.
How to create dynamic PyMongo query to handle ISODate?
Construct var
like a dictionary:
var = { "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISO("2020-01-13 06:43:47.500Z")}]}
and use it like:
col.find(var)
You don't need to convert it to string/JSON.
Try the above and let me know.