Reputation: 834
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
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