warl0ck
warl0ck

Reputation: 3464

Search query string from array list of string of different objects in mongodb

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.

Upvotes: 0

Views: 462

Answers (1)

node_saini
node_saini

Reputation: 812

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;
});

Upvotes: 1

Related Questions