Shiv
Shiv

Reputation: 9

Filter and range operations on pymongo

I have a Mongo database having below values in a collection test

{ "_id" : ObjectId("5a905bb59c92d93d9072c781"), "par1" : 123, "par2" : 777, "par3" : 45 }
{ "_id" : ObjectId("5a905bdc9c92d93d9072c782"), "par1" : 124, "par2" : 787, "par3" : 46 }
{ "_id" : ObjectId("5a905be59c92d93d9072c783"), "par1" : 125, "par2" : 787, "par3" : 47 }
{ "_id" : ObjectId("5a905c039c92d93d9072c784"), "par1" : 12, "par2" : 453, "par3" : 48 }
{ "_id" : ObjectId("5a905c1c9c92d93d9072c785"), "par1" : 12, "par2" : 453, "par3" : 49 }
{ "_id" : ObjectId("5a905c219c92d93d9072c786"), "par1" : 12, "par2" : 453, "par3" : 50 }
{ "_id" : ObjectId("5a905c489c92d93d9072c787"), "par1" : 124, "par2" : 787, "par3" : 46 }
{ "_id" : ObjectId("5a905d339c92d93d9072c788"), "par1" : 124, "par2" : 787, "par3" : 54 }

using pymongo can we do the say filter and range operation in one query and get all the entries corresponding to range and filter. e.g: filter for par1 = 124 and par2 = 787 within the range for par3 = 45 to 54

I tried incorporating aggregate but was unsuccessful. thanks in advance

Upvotes: 0

Views: 417

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38952

Suppose range implies one exclusive of the upper bound, operator expressions for 'par3' field can be combined.

If you'll like to include the upper bound, use lte comparison operator instead of lt comparison operator.

query = {'par1': 124, 'par2': 787, 'par3': {'$gte':45, '$lt': 54}}
cur = collection.find(query)
print(list(cur))

Upvotes: 1

Related Questions