如何在没有根文档的情况下获取子文档?

How to get subdocument without root document?

我有这个 json 文件

{
  "_id": "1",
  "name": "sanggiyo",
  "gender": "Male",
  "children": [
    {
      "name": "tono",
      "gender": "Male",
      "children": [],
      "_id": "2"
    },
    {
      "name": "rin",
      "gender": "Female",
      "children": [],
      "_id": "3"
    }
  ],
  "createdAt": "2022-04-17T11:14:00.648Z",
  "updatedAt": "2022-04-17T11:14:16.277Z",
  "__v": 0
}

我想 children._id 使用

  Person.find( {$or: [ { "_id" : id }, { "children._id" : ObjectId(id) } ]} )

如果我使用 1 的 id,我应该得到所有文档。 但是如果我使用 id 2,我应该只得到没有 id 1 的子对象,有没有办法做到这一点?

您可以尝试使用聚合框架,但在 mongo 查询返回后的代码中使用更具可读性和可维护性的方法 类似于:

const persons = await Person.find({$or: [ { "_id" : id }, { "children._id" : ObjectId(id) } ]});

const result = persons.flatMap(p => [p, ...p.children]).find(p => p._id === id);