skip to Main Content

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> } ):

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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" ] } ] } } )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search