2

i want to find all documents by its first letter.

the case is when i query in mysql then i could do WHERE Stores LIKE 'a%'

the result would be all data with the first letter a.

the question are :

  • How to make the same query using mongoose?
  • how about case-sensitive eg: (a,A). it would be the same query or not?
  • is it necessary to create lowercase_field for this case ?
Good Day
  • 385
  • 7
  • 21

1 Answers1

11

There is a $regex operator for that purpose, the query will look like:

Model.find({"name": {$regex: /^a/, $options: 'i'}}).exec(callback);

and it could be simplified to:

Model.find({"name": /^a/i}}).exec(callback);

In case you need to pass a variable in the query:

var char = 'a';
Model.find({"name": {$regex: '^' + char, $options: 'i'}}).exec(callback);
grkmk
  • 279
  • 5
  • 16
Oleks
  • 1,633
  • 1
  • 18
  • 22