Home > OS >  Fetch documents where at least one element of an array contains a substring
Fetch documents where at least one element of an array contains a substring

Time:07-27

I have a document of the following form in MongoDB:

product = {
    items : Array
}

....sample

{
   "items": ["bananas","apples","grapes","guavas","pineapples"]
}

I want to fetch all documents where one of the items' elements contains a substring called apple

Ideally, apples and pineapples in the array contain the substring apple so the document is supposed to match.

What I've tried with no success

let prods = await Product.find({items: {"$in":["apple"]}); //But not working

Any ideas of a better way would be appreciated.

Thanks

CodePudding user response:

You simply need to check regular expression condition,

  • use $regex operator to check the condition
let prods = await Product.find({
  items: {
    $regex: "apple"
  }
});

Playground

  • Related