使用Mongoose只返回深度嵌套文档中匹配的数组和父字段?

tcomlyy6  于 2023-02-08  发布在  Go
关注(0)|答案(1)|浏览(127)

我在NestJS 9中使用Mongoose 6.9.0和MongoDB 6社区。
我有一个嵌套很深的文档:

{
"_id": "63e28016cc763b6cbd436c47",
...otherfields
    "schools": [
        {
            ...otherfields
            "collections": [
                {
                    ...otherfields
                    "projects": [
                        {
                            "slug_name": "a-dolor-numquam453",
                            "pretty_name": "a dolor numquam453",
                            "description": "Laborum expedita facere tenetur voluptatum. Aut tempore non ex fugit hic amet sapiente modi assumenda. Vitae exercitationem quaerat repellat perspiciatis incidunt. In harum consequuntur quisquam. Dolorem dolores mollitia deserunt dolor fugit esse omnis consectetur explicabo.",
                            "owner": null,
                            "data": [
                                {},{},{},{},etc.
                                ],
                            "_id": "63e28017cc763b6cbd437175",
                            "createdAt": "2023-02-07T16:45:15.863Z",
                            "updatedAt": "2023-02-07T16:45:15.863Z"
                        },
                        ...another_project,
                    ]
                },
                ...another_collection,
            ]
        },
        ...another_school,
    ]
}

我想得到:

  • 根文档中的字段
  • 来自家长学校的字段
  • 父集合中的字段
    *JUST匹配项目中的字段

但我的准则是:

findOne(id: string) {
    const objectId = new mongoose.Types.ObjectId(id);
    return this.rootModel.findOne({ 'schools.collections.projects._id': objectId }, { 'schools.collections.projects.$': 1 }).lean().exec();
}

返回projects数组中的每个项目,包括不匹配的项目。
如何只获取匹配的数组元素(Project),以及项目所属的根字段、学校字段和集合字段?

uxhixvfz

uxhixvfz1#

我想我明白了,这是应该做的吗?

return this.rootModel
      .aggregate([
        { $unwind: '$schools' },
        { $unwind: '$schools.collections' },
        { $unwind: '$schools.collections.projects' },
        { $match: { 'schools.collections.projects._id': objectId } },
        {
          $project: {
            _id: 1,
            ...fields: 1,
            'schools....fields': 1,
            'schools.collections....fields': 1,
            'schools.collections.projects': 1,
          },
        },
      ])
      .exec();

相关问题