Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

python - Pymongo Dynamically generate find query

I am trying to use find_one operator to fetch results from mongodb:

My document structure is as below:

{"_id":{"$oid":"600e6f592944ccc5790f1a9e"},
        "user_id":"user_1",
        "device_access":[
                {"device_id":"DT002","access_type":"r"},
                {"device_id":"DT007","access_type":"rm"},
                {"device_id":"DT009","access_type":"rt"},
           ]
        }

I have created my filter query as below

    filter={'user_id': 'user_1','device_access.device_id': 'DT002'},
           {'device_access': {'$elemMatch': {'device_id': 'DT002'}}}

But Pymongo returns None, when used in a function as below:

#Model.py
#this function in turn calls the pymongo find_one function  
 def test(self):
    doc = self.__find(filter)
    print(doc)

 def __find(self, key):
    device_document = self._db.get_single_data(COLLECTION_NAME, key)
    return device_document

 #Database.py
 def get_single_data(self, collection, key):
    db_collection = self._db[collection]
    document = db_collection.find_one(key)
    return document

. Could you let me know what might be wrong here ?

question from:https://stackoverflow.com/questions/65882419/pymongo-dynamically-generate-find-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your brackets are incorrect. Try:

filter = {'user_id': 'user_1','device_access.device_id': 'DT002', 'device_access': {'$elemMatch': {'device_id': 'DT002'}}}

Also filter is a built-in function in python so you're better off using a different variable name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...