tiltowait
tiltowait

Reputation: 110

MongoDB: Find all subdocuments that match a regex condition

I'm trying to filter MongoDB subdocuments based on regex. I already know that I must use MongoDB's aggregation function, as find() only returns the first document.

Assume I have data in the following format:

{
    "owner": "Jim",
    "pets": [
        { "name": "Max", ... },
        { "name": "Mocha", ... },
        { "name": "Spanky", ... },
        ...
    ]
},
{
    ...
}

Let's say I want to find all of Jim's pets whose name matches a regular expression (say, all pets whose names start with "M"). How might I do this? I've found this question and answer, but it doesn't work because $filter doesn't allow the use of $regex (apparently).

Using MongoDB 5.

Upvotes: 0

Views: 223

Answers (1)

mohammad Naimi
mohammad Naimi

Reputation: 2359

use this :

db.collection.aggregate([
  {
    "$addFields": {
      "ff": {
        "$filter": {
          "input": "$pets",
          "as": "z",
          "cond": {
            "$regexMatch": {
              "input": "$$z.name",
              "regex": "M.*",
              "options": "i"
            }
          }
        }
      }
    }
  }
])

https://mongoplayground.net/p/kdGCYa_H0dT

Upvotes: 1

Related Questions