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

Mongoose聚合查询问题:过滤含isIgnoredUntil的数组对象

Mongoose v7.5.0聚合查询数组过滤问题

需求:过滤eqis数组内的对象,仅保留满足以下条件的条目:

  • 对象存在isIgnoredUntil键
  • 该键的值不为null或空字符串
    不符合条件的对象需要排除。当前编写的聚合查询要么过滤掉所有含isIgnoredUntil键的条目,要么完全没有过滤效果。

数据结构(嵌套在Customer Schema中)

[
    {
        "caseId": "98765",
        "protocols": [
            {
                "_id": "6532454d4fab6bf644091c47"
            },
            {
                "_id": "6532454d4fab6bf644091c48"
            }
        ],
        "reports": [
            {
                "eqis": [
                    {
                        "protocoled": false,
                        "urgency": 0,
                        "_id": "6532454d4fab6bf644091c4a",
                        "isIgnoredUntil": "2023-12-01T12:12:12.000Z"
                    },
                    {
                        "protocoled": false,
                        "urgency": 0,
                        "_id": "6532454d4fab6bf644091c5a"
                    }
                ],
                "_id": "6532454d4fab6bf644091c49"
            }
        ],
        "_id": "6532454d4fab6bf644091c46"
    }
]

当前聚合查询代码

const cases = await Customer.aggregate([
  { $unwind: '$cases' },
  { $match: { 'cases.assignedToUserId': new mongoose.Types.ObjectId(userid) } },
  { $unwind: '$cases.reports' },
  { $unwind: '$cases.reports.eqis' },
  {
    $group: {
      _id: '$cases.caseId',
      eqis: { $push: '$cases.reports.eqis' },
    },
  },
  {
    $project: {
      _id: 0,
      caseId: '$_id',
      eqis: {
        $filter: {
          input: '$eqis',
          as: 'eqi',
          cond: {
            $and: [
              {
                $or: [
                  { $eq: ['$$eqi.urgency', { $min: '$eqis.urgency' }] },
                  { $eq: ['$$eqi.isIgnoredUntil', null] },
                ],
              },
              {
                $lt: ['$$eqi.isIgnoredUntil', new Date()],
              },
            ],
          },
        },
      },
    },
  },
  // Filter out cases with empty eqis array
  {
    $match: {
      eqis: { $not: { $size: 0 } },
    },
  },
  // sort urgency and caseId (asc)
  {
    $sort: {
      'eqis.urgency': 1,
      'cases.caseId': 1,
    },
  },
]);

更新说明

修改后的查询逻辑不太常规,不确定为何能正常运行。现在需要对另一个字段应用类似的过滤逻辑,但添加新条件后,要么无结果返回,要么所有条目都被包含。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:44