2021-03-01

MongoDB - Distribution of number of documents per field count

db.users.aggregate([

    {$project:{

        "field_count": {$size: {$objectToArray:"$$ROOT"}}

    }},

    {$group:{

        "_id": {field_count: "$field_count"},

        "document_count": {$sum: NumberInt(1)},

    }},

    {$project:{

        "field_count": "$_id.field_count"

        , "document_count": 1

        , "_id": 0

    }},

    {$sort: {

        "field_count": -1

    }}

]);


PS. In other words, how many documents exist for each field count (e.g. "78 documents have 5 fields"). 

MongoDB - Collection fields frequency

db.COLLECTION_NAME.aggregate([

    {$project:{

        "arr": {$objectToArray:"$$ROOT"},

    }}, 

    {$unwind: "$arr"},

    {$project: {

        "_id": 0,

        "k": "$arr.k",

    }},

    {$group: {

        "_id": { "k": "$k" },

        "f": {$sum: NumberInt(1)},

    }},

    {$project: {

        "_id": 0,

        "k": "$_id.k",

        "f": 1,

    }},

    {$sort: {

        "f": -1, 

        "k": 1,

    }},

]);


MongoDB - Unwind and show document even if the array is empty

 db.COLLECTION_NAME.aggregate([

    {$unwind: {

        "path": "$FIELD_NAME",

        "preserveNullAndEmptyArrays": true

    }}

]);