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
908 views
in Technique[技术] by (71.8m points)

javascript - Is there a mongo replace method/operator?

In SQL I can do

UPPER(REPLACE(field.name, ' ', '')) LIKE '%" . $input . "%'

which will remove whitespaces and and will convert the string to upper case before comparing it with $input.

Is there a way to do this with mongodb?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The only way I know is to use $where Queries. Consider the example below:

First insert some test data

db.likecoll.insert({"name" : "John Smith"})
db.likecoll.insert({"name" : "Jo hn Smith "})
db.likecoll.insert({"name" : "JohnSmith"})
db.likecoll.insert({"name" : "JohnNOSmith"})

Then run this query to replace spaces on the fly for name field

db.likecoll.find({"$where" : "return this.name.replace(new RegExp(' ', 'g'), '') == 'JohnSmith'" })

The result is

{ "_id" : ObjectId("52f5459eb08622ca2b16ede9"), "name" : "John Smith" }
{ "_id" : ObjectId("52f545adb08622ca2b16edea"), "name" : "Jo hn Smith " }
{ "_id" : ObjectId("52f545b8b08622ca2b16edeb"), "name" : "JohnSmith" }

This should work for you but personally I don't like this approach, mostly becuase this is slow comparing to queries which can be covered with an index. How ever this is also true about your SQL server query.

EDIT:

To convert a string to upper case use str.toUpperCase() javascript function.

Hope it helps!

There is a feature request for this: https://jira.mongodb.org/browse/SERVER-829


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

1.4m articles

1.4m replys

5 comments

57.0k users

...