ArrayElemAt 中的 Mongoose 聚合问题

Mongoose In ArrayElemAt Issue In Aggregate

临时班次等于

[{_id:123,
arr:[{_id:123321,name:"Bluh Bluh",date:"bluh bluh"}] 
}]

所以我想访问 temporaryshifts[0].arr[0] 但我不知道如何访问

$project:{
shiftArr:{$arrayElemAt:['$temporaryshifts',0]}
}

您必须使用 let 运算符才能使用两个 $arrayElemAt 运算符。

db.collection.aggregate([
  {
    "$project": {
      "temporaryshifts": {
        "$let": {
          "vars": {
            "masterKey": {
              "$arrayElemAt": [
                "$temporaryshifts",
                0
              ]
            }
          },
          "in": {
            "$arrayElemAt": [
              "$$masterKey.arr",
              0
            ]
          }
        },  
      }
    },
  },
])

Mongo Playground Sample Execution

为了正确理解我正在举这个例子并假设这是我们的数据

`
[
      {
        _id: 123,
        arr: [
          {
            _id: 123321,
            name: "Bluh Bluh",
            date: "bluh bluh"
          },
          {
            _id: 1233219,
            name: "Bluh Bluh2",
            date: "bluh bluh2"
          }
        ]
      },
      {
        _id: 1234,
        arr: [
          {
            _id: 1233214,
            name: "Bluh Bluh4",
            date: "bluh bluh4"
          }
        ]
      },
      
    ]

`

可以通过此查询获得临时轮班[0].arr[0]

   db.collection.aggregate([
      {
        "$match": {
          "_id": 123
        }
      },
      {
        "$project": {
          shiftArr: {
            $arrayElemAt: [
              "$arr",
              0
            ]
          }
        }
      }
    ])

你需要第一时间匹配得到文档,其余的东西arrayElementAt可以管理。