2023-09-11

MongoDB - Replace regex matched string

 db.collection_name.aggregate([

    {$match: {"target_field": {$exists: true}}},

    {$addFields: {

        "remove": {$regexFind: {

            input: "$target_field", 

            regex: /(.){1,}string_to_match/

        }} 

    }},   

    {$match: {"remove": {$exists: true} }},

    {$addFields: {

        "remove_len": {$strLenBytes: "$remove.match"} 

    }},

    {$addFields: {

        "clean": {$substr: [ 

            "$target_field", 

            "$remove_len",  

            100000]} 

        }},

])

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,

    }},

]);