Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...