Sometimes, we want to perform a full text search in MongoDB and Mongoose and JavaScript.
In this article, we’ll look at how to perform a full text search in MongoDB and Mongoose and JavaScript.
How to perform a full text search in MongoDB and Mongoose and JavaScript?
To perform a full text search in MongoDB and Mongoose and JavaScript, we add indexes to the fields we want to search.
Then we can call find with the $search operator property to do the search.
For instance, we write
const schema = new Schema({
name: String,
email: String,
profile: {
something: String,
somethingElse: String,
},
});
schema.index({ name: "text", "profile.something": "text" });
to create a schema that has a few fields.
Then we add the indexes for the name and profile.something fields with the schema.index method.
Next, we do the search with
MyModel.find({ $text: { $search: searchString } })
.skip(20)
.limit(10)
.exec((err, docs) => {
//...
});
to call find with the $text.$search properties set to searchString to search for searchString.
Then we call exec with a callback and get the results from docs.
Conclusion
To perform a full text search in MongoDB and Mongoose and JavaScript, we add indexes to the fields we want to search.
Then we can call find with the $search operator property to do the search.