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

MongoDB聚合报错:$or为空数组,如何实现仅附近餐厅筛选?

解决MongoDB聚合中$or空数组导致的异常问题

问题出在当用户未选择菜系和标签时,query数组为空,此时$or: []不符合MongoDB的语法规则(要求$and/$or/$nor必须是非空数组),从而抛出异常。

修复方案

动态控制聚合管道中的$match阶段:当有筛选条件(query非空)时,使用$or进行匹配;没有筛选条件时,要么跳过$match阶段,要么用{}匹配所有通过$geoNear筛选的文档。

修改后的完整代码

const query = [];
if (cuisines) {
  const culinaryOptions = {
    culinaryOptions: { $in: cuisines },
  };
  query.push(culinaryOptions);
}
if (tags) {
  const tag = {
    tags: { $in: tags },
  };
  query.push(tag);
}
if (nearest) {
  maxDistance = 10;
  sort = -1;
}

// 构建聚合管道
const pipeline = [
  {
    $geoNear: {
      near: {
        type: 'Point',
        coordinates: [parseFloat(longitude), parseFloat(latitude)],
      },
      distanceField: 'distanceFromMe',
      maxDistance: maxDistance ?? 100 * METERS_PER_MILE, //!*** distance in meters ***!//
      distanceMultiplier: 1 / 1609.34,
      spherical: true,
    },
  },
  // 仅当有筛选条件时添加$match阶段
  ...(query.length > 0 ? [{ $match: { $or: query } }] : []),
  { $unset: ['verificationCode', 'uniqueCode'] },
  { $sort: { location: sort ?? 1 } },
];

return this.restaurantModel.aggregate(pipeline);

另一种等价写法(用空条件匹配所有)

如果不想动态增减管道阶段,也可以直接给$match设置默认条件:

// 替换原来的$match部分
{
  $match: query.length > 0 ? { $or: query } : {},
}

两种方案都能解决空数组异常,同时保留仅用附近筛选的功能——当没有菜系和标签筛选时,所有通过$geoNear筛选的餐厅都会被返回。

内容的提问来源于stack exchange,提问作者saqib sattar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:52:39