4
 {
    "_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"}]}}}
1
  • you can use regular expression $regex or $text. try this : {"array":{$in:[{"title": { $regex:{/Vegetables/}}]}} Commented Oct 12, 2016 at 11:28

2 Answers 2

3

here is what you want:

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

{array: { $elemMatch: { title: { $in: [/Vegetables/, /Fruits/] }}}}
Sign up to request clarification or add additional context in comments.

Comments

0

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"}]}}}

1 Comment

This requires a text index.

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.