Sandeep Ranjan
Sandeep Ranjan

Reputation: 834

Search for text in mongoDB using Mongoose

I have this kind of data in my mongoDB

 {
        "_id" : ObjectId("5a26d554677475818a795f75"),
        "facebookId" : "123456",
        "gender" : "Female",
        "profileUrl" : "https://www.facebook.com/asdfasf",
        "imageUrl" : "/img/profile/sm1.jpg",
        "firstName" : "Anna",
        "token" : "ldhajksdkjasdakjsdajksd",
        "email" : "[email protected]"
    }

here let say i do a query

User.find({firstName:'Anna'},function(err, data){
  console.log(data);
});

It gives me her result but I do firstName:'nna' or firstName:'Ana' or firstName:'anna' or any other combination. So how I can get the closest value for STRING in MongoDB using Mongoose

Upvotes: 0

Views: 785

Answers (1)

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8826

You can filter results by whether they match a regular expression using the $regex operator.

Example:

const queryString = "an";
User.find(
  { firstName: { $regex: `^${queryString}.*`, $options: "i" } },
  (err, data) => {
    console.log(data);
  }
);

This will match all records whose firstName field starts with an (case-insensitive). You can build more complicated regular expressions to match your business requirements.

You can read more about the $regex operator here.

Upvotes: 3

Related Questions