0

I want to search a query string against the array of string stored in array of all the objects presents

my database structure looks like this

[0: 
     destination: ......
     name: ......
     name_list: [""some place", "some place 2", "some place3"]
1:
    destination: ......
    name: ......
    name_list: [""some place4", "some place 5", "some place3"]
2:
    destination: ......
    name: ......
    name_list: [""some place56", "some place 34", "some place3"]

and so on .... 
]

let's say

I want to get all the objects whose name_list array contains string "someplace3" but the query i will receive might only be "place3", since user might not know the complete or exact name. I can't figure how to search, I'am using expressjs module to search in my mongodb database like:

route.find({name_list: "place3"}, function(err, routes) {
    if (err) throw err;
    routeTosend = routes;
});

but obviously I am not getting any results, but if i search exactly like someplace3 it returns all the objects.

I am completely new to database hence mongodb as well, if anyone can help would really appreciate.

1 Answer 1

1

You have to make use of $regex provided by mongodb. You can do something like this

route.find({"name_list": {$regex : /.*places3.*/}}, function(err, routes) {
   if (err) throw err;
   routeTosend = routes;
});

To use variable inside regex you have to create regex object from a string using RegExp constructor

var query= "place"; 
regx = new RegExp('.*' + query + '.*','i');

route.find({"name_list": regx}, function(err, routes) {
   if (err) throw err;
   routeTosend = routes;
});
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the help, worked perfectly, but can i pass variables as well, inside regex expression ?
to use variable inside regex you have to create regex object from a string using RegExp constructor something like this {"name_list" : new RegExp(your_reg_variable)}
something like, var myquery = "place"; {"name_list" : new RegExp(myquery )} but it's not working can you please help me out here.
try to concatenate pattern either in myquery variable or inside constructor
yep, got it, with ` var query= "place"; regx = new RegExp('.*' + variable + '.*','i');`, thanks for the help, can you please update the answer with this as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.