You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB多条件$or查询失效问题求助

问题分析

你的查询返回全量数据的核心原因是:当某个查询参数未传入时,对应的条件会变成{字段名: undefined},MongoDB会将其视为匹配所有缺少该字段或字段值为undefined的文档。比如请求中没传location参数时,{ location }等价于{ location: undefined },而你的数据库文档都没有location字段,这个条件会匹配所有文档,最终$or只要满足任一条件就返回,自然会返回全量数据。

解决方案

动态构建查询条件数组,只保留有有效值的查询条件,排除undefined、空字符串等无效参数。如果需要默认匹配professionalDetails.type: "Cook"和otherDetails.nationality: "Indian",可确保这两个条件在参数未传时也生效(也可根据需求调整逻辑)。

修改后的代码如下:

searchCookForNotification: async function (req, res) {
    let { type = "Cook", nationality = "Indian", firstname, lastname, location } = req.query;

    var db = Person.getDatastore().manager;
    // 动态构建查询条件数组
    const queryConditions = [];

    if (firstname) {
        queryConditions.push({ firstname });
    }
    if (lastname) {
        queryConditions.push({ lastname });
    }
    if (location) {
        queryConditions.push({ location });
    }
    // 按需求加入嵌套字段条件,此处默认保留
    queryConditions.push({ "professionalDetails.type": type });
    queryConditions.push({ "otherDetails.nationality": nationality });

    // 处理无有效条件的极端情况
    const query = queryConditions.length > 0 ? { $or: queryConditions } : {};

    var cooks = await db
      .collection(Person.tableName)
      .find(query)
      .toArray();

    console.log("Length: ", cooks.length);

    return res.successResponse(
      cooks,
      200,
      null,
      true,
      "Cooks found successfully"
    );
  },
};
额外说明
  • 若不需要默认的type和nationality条件,可把这两个判断也放入if语句中,仅当参数传入时才加入条件数组
  • 如果业务需求是多条件同时满足(而非任一满足),直接将$or替换为$and即可

内容的提问来源于stack exchange,提问作者Developer Nans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:50:34