来自嵌套数组的项目对象 MongoDB

Project object from Nested Array MongoDB

[
  {
    "_id": "grandParentId",
    "types": [
      {
        "_id": "parentId",
        "files": [
          {
            "url": "1.example.com",
            "_id": "1childId"
          },
          {
            "url": "2.example.com",
            "_id": "2childId"
          }
        ]
      }
    ]
  }
]

条件:{ _id: 2childId }

预期输出:

{ 
    "url": "2.example.com",
    "_id": "2childId"
}

问题 2:这是一个好方法还是我应该只使用循环来获得所需的输出?

使用聚合 $unwind$project

mongoPlayground

进行测试
db.collection.aggregate([
  {
    "$unwind": "$types"
  },
  {
    "$unwind": "$types.files"
  },
  {
    "$match": {
      "types.files._id": "2childId"
    }
  },
  {
    "$project": {
      "url": "$types.files.url",
      "_id": "$types.files._id"
    }
  }
])

我确定还有其他方法,但您可以使用 mongo 聚合框架:

db.collection.aggregate([
  {
    $match: {
      "types.files._id": "2childId"
    }
  },
  {
    $unwind: "$types"
  },
  {
    $unwind: "$types.files"
  },
  {
    $replaceRoot: {
      newRoot: "$types.files"
    }
  },
  {
    $match: {
      _id: "2childId"
    }
  }
])

第一个$match只是过滤符合您条件的文档。 $unwind 被使用两次来解构不同的数组。 $replaceRoot 将输入文档替换为指定文档(在本例中为子文档,files)和最终 $match 过滤器 files 我们之前根据您的条件解构的数组。首先$match只是为了性能考虑,如果你想删除它。

您可以在 https://mongoplayground.net/p/hoz24xP_BNV

中查看阶段的工作原理

如果您想了解更多信息,请参阅 mongo 聚合框架文档 (https://docs.mongodb.com/manual/aggregation/)