Mongodb conditional query search under an array

Viewed 477

I have a data where an array is there. Under that array Many array of objects is there. I am mentioning the raw data so that anyone guess the structure

{
 _id: ObjectId(dfs45sd54fgds4gsd54gs5),
 content: [
 {
  str: "Hey",
  isDelete: false 
 },
 {
  str: "world",
  isDelete: true
 }
]
}

So I want to search any string that match and I have top search under an array.

So my query is like this:

let searchTerm = req.body.key;
db.collection.find(
 {
  'content.str': {
    $regex: `.*\\b${searchTerm}\\b.*`,
    $options: 'i',
   }
 }
)

So this will return the data. Now for some reason I have to search the data if isDelete: false.

Right now it returns the data whether isDelete is true/false because I have not mentioned the conditon.

Can anyone help me out regarding this to get the data through condition. I want this to Mongodb Query only.

Any help is really appreciated.

2 Answers

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria,

db.collection.find({
  content: {
    $elemMatch: {
      isDelete: true,
      str: {
        $regex: `.*\\b${searchTerm}\\b.*`,
        $options: "i"
      }
    }
  }
},
{
  "content.$": 1
})

Working Playground: https://mongoplayground.net/p/VkdWMnYtGA3

You can add another condition there as belo

db.test2.find({
  $and: [
    {
      "content.str": {
        $regex: "hey",
        $options: "i",
        
      }
    },
    {
      "content.isDelete": false
    }
  ]
},
{
    'content.$':1 //Projection - to get only matching array element
})
Related