case-insensitive query on mongodb

2019-01-26 04:25发布

问题:

is there a way to query for a case-insensitive value on mongo without using map/reduce?

回答1:

Suppose you have document that contains tag field and you want search on it

Tags
{
  tag,
  ...
 }

First option is use regex(but it work slow as @RestRisiko said):

db.tags.find( { "tag" : { "$regex" : "C#", "$options" : "-i" } })

Second option is create another, lower case field( and in mongodb it best way):

Tags
{
  tag,
  tagLower,
  ..
}

And use find as usual:

db.tags.find( { "tagLower" : "c#"})

It will work faster, because above code can use index for search.



回答2:

You have to normalize the data to be queried. Using a regular expression for case-insensitive search might work as well it won't use indexes. So your only option is to normalize. If you need to preserve the original state then you need to denormalize the data and store the normalized values in a dedicated column of the document.



回答3:

When using it with Node.js, it's best to build a RegEx object in the query.

Room.findOne({'name': new RegExp(roomName, 'i')}, {}, function(err, room) {
...


回答4:

Use regular expressions matching as below. The 'i' shows case insensitivity.

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("MSID", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("154800", "i")));

var queryB = Query.And(
       Query.Matches("strName", new BsonRegularExpression("Operation","i")),
       Query.Matches("strVal", new BsonRegularExpression("8221", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);


标签: mongodb