Majid Abdolhosseini
Majid Abdolhosseini

Reputation: 2301

Mongodb Like one of array items

Consider I have a collections which it's document are like this :

{
   "name": "some-name",
   "age": 23,
   "foods" : ["pizza", "cola", "bread", "hotdog"]

}

what I need to achieve is I need to find all documents which has at least one food item which is like for example "pi". so I want one of array items to be like search query string.

Upvotes: 0

Views: 238

Answers (1)

J.F.
J.F.

Reputation: 15177

You can easily do your task using $regex.

So, using this query:

db.collection.find({
  "foods": {
    "$regex": "pi"
  }
})

Mongo will find all documents where foods fields contains at least one item who match the regex "pi".

Example here

Upvotes: 1

Related Questions