search mongoDB by 2 fields

Viewed 455

I have been looking at some other answers on stack overflow and got as far as I could with that. I learnt that I need to create a text index where I define my Schema which I did like this:

productSchema.index({'title': 'text', 'address.city': 'text'});

If I search by just 1 field, ie: title then I get results as I expect.

Product.find( { $text: { $search: searchTerm } } )

But there is something wrong with my query when trying to search by title and city together.

 Product.find( { $text: { $search: searchTerm }, $text: { $search: city } } )

I see no error but I get no results even though I know there should be results for my query. I am not sure if it is because address is an object (according to what I see in Compass)

This is how I defined it in my schema using Mongoose

address: {
    city: {type: String, required: true }
},

If I do this:

Product.find().and([{ title: searchTerm }, { 'address.city': city }])

it almost works. But I have to type in the exact title of the product. If the product is called "a rubber duck" and I type in "duck" I get no results. If I type in "a rubber duck" and select the city it is listed in I get back a result.

I have just also tried this:

Product.find( { $and: [ {$text: { $search: searchTerm }}, { address: {city : city } }  ] } )

Which seems to work but could probably be improved upon!

1 Answers

Have you looked into the link below?
https://docs.mongodb.com/manual/reference/operator/query/or/
There you can find how to add multiple expressions in same query. If you want to search for titles where title might be equal to A or to B use a query like this: db.inventory.find( { $or: [ { title: "A" }, { title: "B"} ] } ).
Edit
If you need data from db to match both expressions in query then use something like this:
Product.find( { $and: [{ address:{city: "CityName"} }, { address: {country : "UK" } } ] } )

Related