Home > OS >  PyMongo Query | How to ingore a parameter
PyMongo Query | How to ingore a parameter

Time:05-30

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.

  1. $and - Match 1.1. and 1.2. conditions.

    1.1. Match first_name and last_name.

    1.2. $or- Match age variable is null or age field match with age variable.

db.find_one({
  $and: [
    {
      "first_name": firstname,
      "last_name": lastname
    },
    {
      $or: [
        {
          $expr: {
            $eq: [
              null,
              age
            ]
          }
        },
        {
          "age": age
        }
      ]
    }
  ]
})

Sample Mongo Playground

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" ] } ] } } )
  • Related