$switch 在 $match MONGODB 中

$switch inside a $match MONGODB

您好,我正在尝试在 TIBCO jasperstudio 中使用 MONGODB 查询来创建报告

我想做的是使用两个参数@orderitemuid 和@ordercatuid 过滤数据。我的情况是,如果我使用@orderitemuid 放置一个参数,它将忽略@ordercatuid 的参数。反之亦然,如果我使用@ordercatuid 放置一个参数,它将忽略@orderitemuid 的参数。但是在查询中使用机器人参数时也有一个选项。我在 $match 中使用了 $switch,但出现错误。下面是我正在使用的 $match

{
    $match: {
        $switch: {
            branches: [
                {
                    case: { $eq: [{ $IfNull: [$P{orderitemuid}, 0] }, 0] },
                    then: { 'ordcat._id': { '$eq': { '$oid': $P{ordercatuid} } } },
                },
                {
                    case: { $eq: [{ $IfNull: [$P{ordercatuid}, 0] }, 0] },
                    then: { '_id': { '$eq': { '$oid': $P{orderitemuid} } } },
                },
            ],
            default: {
                $expr: {
                    $and: [
                        { $eq: ['_id', { '$oid': $P{orderitemuid} }] },
                        { $eq: ['ordcat_id', { '$oid': $P{ordercatuid} }] },
                    ],
                },
            },
        },
    },
}

提前致谢

$match docs

中所述

$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. ...

$switch是聚合表达式。这意味着它不能在 $match 阶段使用而不用 $expr.

包装

但是您可以用 $expr 包裹它,这也需要您稍微重构 return 值,如下所示:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $switch: {
          branches: [
            {
              case: {
                $eq: [
                  {
                    $ifNull: [
                      $P{orderitemuid},
                      0
                    ]
                  },
                  0
                ]
              },
              then: {
                $eq: [
                  "$ordcat._id",
                  {"$oid":$P{ordercatuid}}
                ]
              }
            },
            {
              case: {
                $eq: [
                  {
                    "$ifNull": [
                      $P{ordercatuid},
                      0
                    ]
                  },
                  0
                ]
              },
              then: {
                $eq: [
                  "$_id",
                  {"$oid":$P{orderitemuid}}
                ]
              }
            }
          ],
          default: {
            $and: [
              {
                $eq: [
                  "$_id",
                  {"$oid": $P{orderitemuid} }
                ]
              },
              {
                $eq: [
                  "$ordcat_id",
                  {"$oid": $P{ordercatuid}}
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground