0

I am trying to filter not just the fields but objects inside my array field. Referring to the example below, for segments field, I want my client to only get those objects in the segments array where isReleased === true

Example Schema

{
    _id:      123456,
    segments: [
        {
            name: 'Type A',
            isReleased: false,
        },
        {
            name: 'Type B',
            isReleased: false,
        },
        {
            name: 'Type C',
            isReleased: true,
        }
    ],
}

So basically, I want my client to just receive,

{
    _id:      123456,
    segments: [
        {
            name: 'Type C',
            isReleased: true,
        }
    ],
}
nupac
  • 2,459
  • 7
  • 31
  • 56
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Tomasz Lenarcik Oct 30 '16 at 20:24

1 Answers1

0

You could use the $elemMatch operator. The query would be like this:

Schema.find({segments: {$elemMatch: {isReleased: true}}},...)

You can check the examples on the link for more details.

andresk
  • 2,845
  • 1
  • 13
  • 17