Home > Blockchain >  Pymongo : Ignore null input value when searching documents
Pymongo : Ignore null input value when searching documents

Time:10-31

In mongodb i have many document structure like this in root collection

 _id: ObjectId()
 A : "a"
 B : "b"

 _id:ObjectId()
 A : "c"
 B : "d"

And then i want to find document depend on user input, for example

data = request.data
item_A = data.get('A', None)
item_B = data.get('B', None)
for item in root.find({
    'A': item_A,
    'B': item_B
}):
    print(item)

but the problem is if the user just want to find document depend on A and dont have input value for item_B then item_B will be None, so that the code don't return anything. Any suggestion?

CodePudding user response:

You just need to built the query properly, if B input is None then just ignore it in the query - you can do this in many ways here is one example:

data = request.data
item_A = data.get('A', None)
item_B = data.get('B', None)
query = {}

if item_A is not None:
    query['A'] = item_A
    
if item_B is not None:
    query['B'] = item_B
    
for item in root.find(query):
print(item)

EDIT

Another way for example is to create a dynamic query replacement.

data = request.data
item_A = data.get('A', { "$exists": True })
item_B = data.get('B', { "$exists": True })

for item in root.find({
    'A': item_A,
    'B': item_B
}):
    print(item)
  • Related