【问题标题】:MongoDB: get documents by last element value in nested arrayMongoDB:通过嵌套数组中的最后一个元素值获取文档
【发布时间】:2022-11-20 23:48:17
【问题描述】:

这个问题与其他问题略有不同,因为我需要获取整个文档而不仅仅是特定字段。

我需要根据嵌套数组的最后一个元素值过滤文档(所有文档,而不仅仅是特定字段)。 (doc.array[i].innerArray[innerArray.length - 1].desiredField)

文档看起来像这样:

[
  {
    "_id": 0,
    "matches": [
      {
        "name": "match 1",
        "ids": [
          {
            "innerName": "1234"
          },
          {
            "innerName": "3"
          }
        ]
      }
    ]
  },
  {
    "_id": 1,
    "matches": [
      {
        "name": "match 5",
        "ids": [
          {
            "innerName": "123"
          },
          {
            "innerName": "1"
          }
        ]
      },
      {
        "name": "match 5",
        "ids": [
          {
            "innerName": "1"
          },
          {
            "innerName": "1234"
          },
          
        ]
      },
      
    ]
  }
]

所以如果我们按照 innerName = '1234' 过滤,结果是这样的:

{
    "_id": 1,
    "matches": [
      {
        "name": "match 5",
        "ids": [
          {
            "innerName": "123"
          },
          {
            "innerName": "1"
          }
        ]
      },
      {
        "name": "match 5",
        "ids": [
          {
            "innerName": "1"
          },
          {
            "innerName": "1234"
          },
          
        ]
      }

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    一种选择是:

    db.collection.find({
      $expr: {
        $in: [
          "1234",
          {$reduce: {
              input: "$matches",
              initialValue: [],
              in: {$concatArrays: ["$$value", [{$last: "$$this.ids.innerName"}]]}
            }
          }
        ]
      }
    })
    

    查看它在playground example 上的工作原理

    【讨论】:

      【解决方案2】:

      另外的选择:

      db.collection.aggregate([
      {
      $match: {
        $expr: {
          $gt: [
            {
              $size: {
                $filter: {
                  input: "$matches",
                  cond: {
                    $in: [
                      {
                        $last: "$$this.ids.innerName"
                      },
                      [
                        "1234"
                      ]
                    ]
                  }
                }
              }
            },
            0
          ]
        }
       }
      }
      ])
      

      解释:

      对于最后一个嵌套数组元素中具有“1234”的文档,仅匹配数组大小 >0 的文档。

      Playground:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-18
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-06
        • 2020-11-18
        • 2023-03-05
        相关资源
        最近更新 更多