mongodb 在子文档数组的数组中获取不同的项目

mongodb get distinct items in array of subdocument array

我有:

我有一个患者集合,每个患者都有一组治疗的子文档。

每个治疗都有一个诊断数组(简单字符串)

我想要的

我想得到所有没有治疗的患者(但有他们所有诊断的数组!)

我也想获得没有重复(不同)的诊断数组

数据现在的样子

[
    {
        "_id": "5e517d80da6c3746d416f918",
        "firstName": "israel",
        "lastName": "k",
        "maritalStatus": "Single",
        "createdBy": "5e4d918ba81c963ed8d51d25",
        "createdAt": "2020-02-22T19:14:08.152Z",
        "__v": 1,
        "lastTreatment": "2022-03-08T20:29:25.779Z",
        "treatments": [
            {
                "diagnoses": [
                    "a",
                    "b"
                ],
                "_id": "5e6555a51567d032640a72f7",
                "visitReason": "balba",
                "treatmentNumber": 1,
                "createdBy": "5e4d918ba81c963ed8d51d25",
                "treatmentDate": "2022-03-08T20:29:25.779Z"
            },
            {
                "diagnoses": [
                    "a",
                    "c"
                ],
                "_id": "5e6555a51567d032640a72f7",
                "visitReason": "blabla",
                "treatmentNumber": 2,
                "createdBy": "5e4d918ba81c963ed8d51d25",
                "treatmentDate": "2022-03-08T20:29:25.779Z"
            }
        ]
    },
]

我想如何获取数据

[
    {
        "_id": "5e517d80da6c3746d416f918",
        "firstName": "israel",
        "lastName": "k",
        "maritalStatus": "Single",
        "createdBy": "5e4d918ba81c963ed8d51d25",
        "createdAt": "2020-02-22T19:14:08.152Z",
        "__v": 1,
        "lastTreatment": "2022-03-08T20:29:25.779Z",
        "diagnoses": ["a","b","c"]
    },
]

如何使用 MongoDB 聚合框架来实现?

您可以 运行 $max to get lastTreatment and $reduce along with $setUnion 获得独特的诊断:

db.collection.aggregate([
    {
        $project: {
            _id: 1,
            firstName: 1,
            lastName: 1,
            maritalStatus: 1,
            createdBy: 1,
            createdAt: 1,
            __v: 1,
            lastTreatment: { $max: "$treatments.treatmentDate" },
            diagnoses: {
                $reduce: {
                    input: "$treatments",
                    initialValue: [],
                    in: { $setUnion: [ "$$value", "$$this.diagnoses" ] }
                }
            }
        }
    }
])

Mongo Playground