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

我需要根据嵌套数组的Last Elements值过滤文档(所有文档,而不仅仅是特定的字段).(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"
          },
          
        ]
      }

推荐答案

一种 Select 是:

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

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

MongoDB—基于数组中同一文档中的另一个字段更新字段

Mongo聚合项目数组交集

数组相等条件返回的文档多于与相等匹配的文档:MongoDB

Golang mongodb聚合错误:管道阶段规范对象必须包含一个字段

Mongo $sort然后$group,顺序能保证吗?

Golang:如何判断 collection.Find 是否没有找到任何文件?

mongo:在 mongodb 6.0 docker 容器上找不到命令

无法提取地理键,经度/纬度超出范围

使用 Spring Boot >= 2.0.1.RELEASE 将 ZonedDateTime 保存到 MongoDB 时出现 CodecConfigurationException

Node.js 数据库的抽象层

加载时将 mongo 存储的日期转换回自 Unix 纪元以来的毫秒数?

django 和 mongodb 是否使迁移成为过go ?

`fields cannot be identical'和''` mongoimport错误

如何使用原子操作在一个文档中切换布尔字段?

有没有办法将python对象直接存储在mongoDB中而不序列化它们

如何使用node.js http服务器从mongodb返回大量行?

Java Mongodb 正则表达式查询

如何在 MongoDB 中删除此弃用警告,为什么会这样?

单个语句中的多个 mongo 更新运算符?

AsQueryable 方法是否在新的 Mongodb C# 驱动程序 2.0rc 中离开?