Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You simply need to check regular expression condition,

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

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading