如何在MongoDB中制作一个过滤器,然后切片一些数组?

我try 了这个聚合,但得到了一个错误.我认为问题出在项目阶段.项目阶段不能接受两个表达式.还有别的办法吗?

 [
  {
    $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]
      },
    },
  },
]

推荐答案

您应该需要一个额外的$set/$project阶段,以便使用$slice运算符设置queue字段.

{
  $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运算符,其 struct 应为:

queue: {
  $last: /* $filter operator */
}

Mongodb相关问答推荐

MongoDB聚合:将文档列表转换为列表

在MongoDB中获取所有帖子时如何获取相关用户信息

如何在 MongoDB 中的集合下查找同一文档

Mongodb 按数组元素聚合组

如何在 go mongo-driver 中为 options.FindOne() 设置限制

MongoDB聚合:如何将查找结果放入嵌套数组中?

如何使用 Golang 库获取 MongoDB 版本?

类型错误:db.close is not a function

mongodb:多键索引 struct ?

MongoError:$subtract 累加​​器是一元运算符

Meteor 中的平均聚合查询

Golang/mgo:如何让 MongoDB 在字段中使用当前时间?

为什么不建议在 MongoDB 中使用服务器端存储函数?

将 JSON 与 MongoDB 一起使用?

如何在mongoose中加入两个集合

直接从 URL 查询字符串提供的 mongo 查询有多危险?

PyMongo 中的警告消息:count is deprecated

我在更新中对 $set 和 $inc 做错了什么

如何在 golang 和 mongodb 中通过 id 查找

将日期从毫秒转换为 ISODate 对象