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

    }}

]);

2020-12-26

MongoDB - How to update a doubly nested array of objects

 db.COLLECTION.update(

    {

        "any_field": "any_value"

    }

    , {$set: {

        "parent.$[x].child.$[xx].grandchild": "any_value"

    }}

    , {

        arrayFilters: [

            {"x.any_matching_field": "any_value"}

            , {"xx.any_matching_field": "any_value"}

        ]

        , multi: true

        , upsert: false

    }

);

2020-12-22

JavaScript - Regex replace with matches

let str = 'abc def SOMETHING_TO_LOOK_FOR 12';

str = str.replace(

    /(.*)SOMETHING_TO_LOOK_FOR ([0-9]{1,})(.*)/

    , "$1 ANY_OTHER_TEXT $2 $3"

);

console.log(str);


JavaScript - Extract the string between first set of curly brackets

let re = /{([^}]+)}/;

let matches = re.exec(str);

console.log(matches[1]);


2020-12-17

MongoDB - Filter based on sibling fields (2 fields in the same document)

db.COLLECTION.aggregate([   

    {$match: { 

        $expr: {

            $eq: ["$field1", "$field2.subfield3"]

        }

    }}

]);