Thanh Dao
Thanh Dao

Reputation: 1260

How to search by many value in array using mongoDB?

I have data object like as :

{
  "openingTime": ['Mon','Fri','Sat','Sun']
}

If I search with string 'Mon Sat Sun', return TRUE. If I search with string 'Mon Web Sun', return FALSE.

Please help me, or give a keyword. Thanks a lot!

Upvotes: 0

Views: 69

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

You want $all which is basically an $and condition but with nicer syntax:

db.hello.find({ "opening_time": { "$all": [ "Mon", "Sat", "Sun" ] } })

Or in the failing case:

db.hello.find({ "opening_time": { "$all": [ "Mon", "Wed", "Sun" ] } })

Since "Wed" is not a value in the array then it is not a match.

This is the nicer form of:

db.hello.find({ "$and": [ 
    { "opening_time": "Mon" },
    { "opening_time": "Sat" },
    { "opening_time": "Sun" }
]})

Which means you need "all" of the conditions to be met in order to make this true.

If you have a string, then just "split" it to form the array argument:

var string = "Mon Sat Sun";

db.hello.find({ "opening_time": { "$all": string.split(" ") } })

Upvotes: 1

Related Questions