PyMongo 查询 |如何忽略参数

PyMongo Query | How to ingore a parameter

有没有办法在一行中使用pymongo查询文档时忽略某个参数,例如:

db.find_one( { "first_name": firstname, "last_name": lastname, "age": age if age else <ignore this field from querying all together> } ):

使用 $and$or 运算符。

  1. $and - 匹配 1.1.1.2. 条件.

    1.1。匹配 first_namelast_name.

    1.2。 $or- 匹配 age 变量为空或 age 字段与 age 变量匹配。

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

Sample Mongo Playground

您可以尝试以下几种方法:

filter = { "first_name": firstname, "last_name": lastname }
if age:
    filter["age"] = age

collection.find_one(filter)

-或-

filter = { "first_name": firstname, "last_name": lastname }
age_filter = { "$expr": { "$eq": [ "$age", { "$ifNull": [ age, "$age" ] } ] } }
filter.update(age_filter)
collection.find_one(filter)

-OR-(同上)

collection.find_one({ "first_name": firstname, "last_name": lastname, "$expr": { "$eq": [ "$age", { "$ifNull": [ age, "$age" ] } ] } } )