how to split string with empty space and also remove numbers from a string in mongodb?

I have this document, i need to split string using empty space and also remove numbers from a string in mongodb aggregation :

{
  "_id":"1",
  "foo":"alpha069",
  "faa":"alpha"
}

I want to get this:

{
  "_id":"1",
  "foo":"alpha069",
  "faa":"alpha",
  "new_foo":"alpha",
  "new_faa":["a","l","p","h","a"]
}

1 answer

  • answered 2021-01-11 08:56 turivishal

    This kind of operations in query may cause performance issues, if you really want in query then try $function, starting from MongoDB v4.4, Write JS code inside function,

    • $addFields to add new field converted you can change as per your need,
    • $function pass both fields in args
    • body foo.replace(/\d+/g, ''), this will remove digits from string, you can change if you have better expression for replace
    • faa.split("") this will split string using empty string
    db.collection.aggregate([
        {
            $addFields: {
                converted: {
                    $function: {
                        body: function(foo, faa) {
                            return {
                                foo: foo.replace(/\d+/g, ''),
                                faa: faa.split("")
                            }
                        },
                        args: ["$foo", "$faa"],
                        lang: "js"
                    }
                }
            }
        }
    ])