如何在 mongo 数据库中有条件地匹配一个字段

How to $match a field conditionally in mongo DB

我有以下架构:

User: {
...otherFields,
isDumb: false,
type: "A" // could be "A", "B", or "C"
}

我想默认获取所有 dumb 用户,仅当 type 通过参数传递时才按 type 获取。

    static async getUsers(req: any, res: Response) {
        const { type = "" } = req.params;
        const queryPipeline = [
            {
                $match: {
                    isDumb: true,
                    type: // I want to only filter by type if the param is passed in
                }
            }
         ]
         const users = await User.aggregate(queryPipeline);

所以如果我的数据是:

[
  {
    ...otherFields,
    isDumb: false,
    type: "A"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "C"
  }
]

req.params.type是“B”,我应该回来:

[
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  }
],

如果 req.params.typeundefined,我应该得到所有 dumb 用户

[
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "C"
  }
]

您只需构建一个对象并将其传递给匹配

const matchParams = req.params.type ? {isDumb:true,type:req.params.type } : {isDumb:true }

您可以使用JS创建对象:

const params = "A" // get req.params as you want
let query = {$match:{isDumb:true}}
if(params) query.$match.type = params

console.log(query)

首先,您不需要使用聚合框架进行简单的查找查询。您可以改用 find 方法。

其次,考虑使用 isDumb: true 初始化过滤器的方法,并仅在 req.params.type 存在时才添加新的 type 属性。

let filter = { isDumb: true };
if(req.params.type) filter.type = req.params.type;

const users = await User.find(filter);