MongoDB - 如何过滤并获取数组字段中的最后数据

问题描述 投票:0回答:1

如何制作过滤器,然后在 MongoDB 中对某些数组进行切片?

我尝试过这个聚合,但出现错误。我认为问题出在项目阶段。项目阶段不能接受两个表达式。还有别的办法吗?

 [
  {
    $match: {
      _id: ObjectId("65a739bc29c608fd90b65038"),
    },
  },
  {
    $project: {
      date: 1,
      serviceScheduleId: 1,
      serviceId: 1,
      branchOfficeId: 1,
      queue: {
        $filter: {
          input: "$queue",
          cond: {
            $and: [
              {
                $eq: [
                  "$$this.user.status",
                  "waiting",
                ],
              },

            ],
          },
        },
        $slice:{"$queue",1]
      },
    },
  },
]
mongodb aggregation-framework aggregate
1个回答
1
投票

您应该需要额外的

$set
/
$project
阶段来使用
queue
运算符设置
$slice
字段。

{
  $project: {
    ...,
    queue: {
      $filter: {
        input: "$queue",
        cond: {
          $and: [
            {
              $eq: [
                "$$this.user.status",
                "waiting"
              ]
            }
          ]
        }
      }
    }
  }
},
{
  $set: {
    queue: {
      $slice: ["$queue", 1]
    }
  }
}

或者将整个

$filter
运算符作为
$slice
运算符的第一个参数。

{
  $project: {
    ...
    queue: {
      $slice: [
        {
          $filter: {
            input: "$queue",
            cond: {
              $and: [
                {
                  $eq: [
                    "$$this.user.status",
                    "waiting"
                  ]
                }
              ]
            }
          }
        },
        1
      ]
    }
  }
}

要获取数组的最后一个元素,请使用

$last
运算符,结构应为:

queue: {
  $last: /* $filter operator */
}
© www.soinside.com 2019 - 2024. All rights reserved.