1

I have documents akin to the following format:

img1

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?

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • If you need to search all fields, you might try creating a text index https://stackoverflow.com/a/35843354/11746212 – IronMan Jul 09 '19 at 22:42
  • Possible duplicate of [Checking if a field contains a string](https://stackoverflow.com/questions/10610131/checking-if-a-field-contains-a-string) – buræquete Jul 10 '19 at 00:21

3 Answers3

1

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' }
});
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
0

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/ });
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

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.

Rajat Goel
  • 2,207
  • 17
  • 35