'Mongoose match regex on subdocuments array

Is it possible to use $match inside an aggregate on a subdocument array ?

Here's what I have:

mainModel.js

const mainModelSchema = mongoose.Schema({
  name: {
    type: String,
    required: [true, 'mainModel name required']
  },
  arr: {
    type: [subModel.schema],
    default: []
  },
});

const mainModel = mongoose.model('mainModel', mainModelSchema);

subModel.js

const subModelSchema = mongoose.Schema({
  a: {
    type: String,
    required: [true, 'subModel a required']
  },
});

const subModel = mongoose.model('subModel', subModelSchema);

My first aggregate request (this is working fine) :

mongoose.model('mainModel').aggregate([
  {
    $match: {
      { name: { '$regex': '.*someValue.*', '$options': 'i' } },
    }
  }
])

My second aggregate request (this is not working) :

mongoose.model('mainModel').aggregate([
  {
    $match: {
      { 'arr.a': { '$regex': '.*someValue.*', '$options': 'i' } },
    }
  }
])

I'd like to be able to filter documents using a regex on a field located inside a subdocument array.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source