MongoDB:通过嵌套数组中最后一个元素值获取文档

50few1ms  于 2022-11-22  发布在  Go
关注(0)|答案(2)|浏览(152)

这个问题与其他问题略有不同,因为我需要获得整个文档,而不仅仅是特定字段。
我需要根据嵌套数组的最后一个元素值来过滤文档(所有文档,而不仅仅是特定字段)。(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"
          },
          
        ]
      }
vc6uscn9

vc6uscn91#

一个选项是:

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

了解它在playground example上的工作原理

egmofgnx

egmofgnx2#

另一个选项:

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

解释道:
对于最后一个嵌套数组元素中包含“1234”的文档,仅匹配数组大小〉0的文档。
Playground:

相关问题