Search code examples
mongodbmongoosemongodb-querymongoose-schemamongoose-populate

how to find all documents with only looking at first letter of the values in mongoose


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 ?

Solution

  • 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);