2023-09-01

MongoDB - Distinct list of keys in a collection or sub-document

 db.authors.aggregate([

    {$project: {"array": {"$objectToArray": "$sub_doc_field_name"}}},

    {$unwind: "$array"},

    {$project: {

        "key": "$array.k"

    }},

    {$group: {

        _id: "$key",

        count: {$sum: 1},

    }},

    {$addFields: {

        key: "$_id",

    }},

    {$project: {

        _id: 0,

    }},

    {$sort: {

        key: 1,

    }},

]);


No comments:

Post a Comment