【问题标题】:Mongoose In ArrayElemAt Issue In AggregateArrayElemAt 聚合中的 Mongoose
【发布时间】:2021-09-13 05:26:05
【问题描述】:

临时班次等于

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

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

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

【问题讨论】:

    标签: database mongodb mongoose aggregate


    【解决方案1】:

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

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

    Mongo Playground Sample Execution

    【讨论】:

      【解决方案2】:

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

      `
      [
            {
              _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 可以管理的其余部分。

      【讨论】:

        猜你喜欢
        • 2018-01-30
        • 1970-01-01
        • 2014-08-09
        • 2017-11-27
        • 2017-05-23
        • 2017-01-20
        • 2015-06-28
        • 2020-02-01
        • 2015-10-04
        相关资源
        最近更新 更多