Query on objects contained within an array of objects

In an array of objects, I want to find all objects that has a certain key-value pair and store them all in a different variable.

const productSchema = new Schema(
  {
    variants: [
      {
        attrs: {},
      },
    ],
  },
  { minimize: false, timestamps: true }
);

I believe you need to use the $elemMatch operator for this one.
What you would do is, query for the field you want to return where you use $elemMatch to see the nested field that equals what you are looking for.

1 Like