ArrayElemAt 中的猫鼬问题在聚合中

时间:2021-07-01 06:14:51

标签: database mongodb mongoose aggregate

临时班次等于

textDirection: AppCubit.get(context).postsLang[index].toString() == 'ar' ?TextDirection.rtl:TextDirection.ltr,

所以我想访问临时班次[0].arr[0] 但我不知道如何访问

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

2 个答案:

答案 0 :(得分:1)

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

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

Mongo Playground Sample Execution

答案 1 :(得分:0)

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

`
[
      {
        _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可以管理的其他东西。