Midhunsai
Midhunsai

Reputation: 427

how can i find text search in an array in mongodb

 {
    "_id":objectId(23651478),
    "name":"Tomatos"
    "array":[
             {"title":"Vegetables"}
            ]
    "description":"Vegitables are good to health"
 },
 {
    "_id":objectId(45761244),
    "name":"Apples"
    "array":[
             {"title":"Fruits"}
            ]
    "description":"Fruits are good to health, vegitables are also good to health"
 },
 {
    "_id":objectId(45761244),
    "name":"Apples"
    "array":[
             {"title":"Vegetables-home-made"}
            ]
    "description":"Fruits are good to health, vegitables are also good to health"
 }

Above is my mongo schema modal for my project requirement. When I want to search for vegetables only, vegetable name should have to come. If I search for both vegetables and fruits, both names ie., Tomato and Apple should have to come.

I used "$in" operator like this

{"array":{$in:[{"title":"Vegetables"},{"title":"Fruits"}]}}

It is giving only documents that have the title Vegetables and not the Vegetables-Home-made. For that I tried to use $elemMatch

 {"array":{$elemMatch:[{"title":"Vegetables"},{"title":"Fruits"}]}}

But when we search for multiples ie., Vegetables and Fruits in elemMatch, it is giving an error, I want a text search in a array for particular title key only ie.,

{"array":{$text:{:$search:[{"title":"Vegetables"},{"title":"Fruits"}]}}}

Upvotes: 4

Views: 4156

Answers (2)

chirag
chirag

Reputation: 1779

here is what you want:

you can use regular expression within $in operator like this :

{array: { $elemMatch: { title: { $in: [/Vegetables/, /Fruits/] }}}}

Upvotes: 3

Rotem
Rotem

Reputation: 1379

The general text search in MongoDB looks like that:

db.collectionName.find( { $text: { $search: "Vegetables" } } )

Please check the search text you are running the word Vegetables contains a spelling error in it:

{"array":{$text:{:$search:[{"title":"Vegitables"},{"title":"Fruits"}]}}}

Upvotes: 0

Related Questions