I have documents akin to the following format:
When a user performs a search, they send an array to the backend. This array contains at least one element.
Say that they send ['javascript']
to the backend. Is there a way to query MongoDB to find out with documents contain the word javascript
?
I tried something like,
db.find({ body: { $all:['javascript'] } });
but that only works if body
is an array as well. Any way to accomplish this?
you could use a pipe-delimited regex pattern with the keywords list like this:
const subStrings = ["javascript", "php", "python"];
const regex = subStrings.join("|");
db.find ({
body: { $regex: regex, $options: 'i' }
});
Use the $regex
operator and pass it a regex contained in a string:
db.find({ body: { $regex: ".*javascript.*" }});
You could also do this:
db.find({ body: /.*javascript.*/ });
db.find({ body: /javascript/ });
First, you need to create a text index on the fields you want to search on. If you want to search on all fields
db.collection.createIndex( { "$**": "text" } )
Or if you want to include only few specific fields, than
db.collection.createIndex( { title: "text", body: "text" } )
You can add weightage also, for eg. in your case title should be having more weightage than description.
Then you can have a search like:
db.collection.find( { $text: { $search: "java javascript python" } } )
this will search for all documents which contains any or all these words.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.