Is there a way to ignore a parameter when querying documents using pymongo in one line, for example:
db.find_one( { "first_name": firstname, "last_name": lastname, "age": age if age else <ignore this field from querying all together> } ):
CodePudding user response:
Work with $and
and $or
operators.
$and
- Match 1.1. and 1.2. conditions.1.1. Match
first_name
andlast_name
.1.2.
$or
- Matchage
variable is null orage
field match withage
variable.
db.find_one({
$and: [
{
"first_name": firstname,
"last_name": lastname
},
{
$or: [
{
$expr: {
$eq: [
null,
age
]
}
},
{
"age": age
}
]
}
]
})
CodePudding user response:
Here are couple of ways you can try:
filter = { "first_name": firstname, "last_name": lastname }
if age:
filter["age"] = age
collection.find_one(filter)
-OR-
filter = { "first_name": firstname, "last_name": lastname }
age_filter = { "$expr": { "$eq": [ "$age", { "$ifNull": [ age, "$age" ] } ] } }
filter.update(age_filter)
collection.find_one(filter)
-OR- (same as above)
collection.find_one({ "first_name": firstname, "last_name": lastname, "$expr": { "$eq": [ "$age", { "$ifNull": [ age, "$age" ] } ] } } )