Case insensitive search in Mongo

前端 未结 5 2077
时光说笑
时光说笑 2020-11-29 21:04

I am using a case insensitive search in Mongo, something similar to https://stackoverflow.com/q/5500823/1028488.

ie I am using a regex with options i. But I am am ha

5条回答
  •  星月不相逢
    2020-11-29 21:28

    UPDATE: As of MongoDB 2.4 one would use a "text" index and full text search query to do this. You can read about them here. If using a recent MongoDB the approach below would be silly and unecessary.

    However, if you have MongoDB < 2.4.0 you could use a regular expression like so:

    > db.reg.insert({searchword: "win"})
    > db.reg.insert({searchword: "window"})
    > db.reg.insert({searchword: "Win"})
    
    > db.reg.find()
    { "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
    { "_id" : ObjectId("4ecd2e36dd68c9021e453d13"), "searchword" : "window" }
    { "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }
    
    > db.reg.find({ searchword: /^win$/i })
    { "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
    { "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }
    

    However, your version wasn't working because you don't need the "/"s when using the $regex operator:

    > db.reg.find({ searchword: { $regex: "^win$", $options: '-i' }})
    { "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
    { "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }
    

    Please note that case insensitive queries do not use the index so it might make sense to make a lowercase searchword field so that you can speed that query up.

    Go here for more info on RegularExpressions

提交回复
热议问题