Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

aggregate - 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"]
}
question from:https://stackoverflow.com/questions/65661678/how-to-split-string-with-empty-space-and-also-remove-numbers-from-a-string-in-mo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
                }
            }
        }
    }
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...