Array Filter Embedded

Good night guys, help me out there…

I have a collection that has an array…

Example:

{
      _id: "something",
      array: [
         {
          "name": "name 1",
          "other field": 1
          },
          {
          "name": "name 2",
          "other field": 1
           },
          {
          "name": "name 3",
          "other field": 1
          }
      ]
}

I’m using NodeJS and I’m trying to do a FindOne through the _id… but I want to return only a specific array element and one or more specific fields…

Example…

db.collection.findOne({ _id: _id}, { _id: 0, "array.0.field": 1})

I’ve turned the internet and the docs upside down and haven’t found a way to do this…

The funny thing is that with the update methods… if I do… “array.0.campo”… it works… but with findOne it doesn’t

I even used $elemMatch… but it doesn’t allow returning specific fields…

Hi @Lucas_Almeida and welcome to MongoDB community forums!!

Based on the above sample document, I tried to insert the document as:

Atlas atlas-b8d6l3-shard-0 [primary] test> db.filter.find()
[
  {
    _id: ObjectId("6440e61fd80fa2295ca82d76"),
    array: [
      { userId: ObjectId("6440e6a3d80fa2295ca82d77"), name: 'test1' },
      { userId: ObjectId("6440e6a3d80fa2295ca82d78"), name: 'test2' },
      { userId: ObjectId("6440e6a3d80fa2295ca82d79"), name: 'test3' }
    ]
  }
]

and used the following query using $elemMatch

const filter = {
    '_id': new ObjectId('6440e61fd80fa2295ca82d76')
  };
  const projection = {
    'array': {
      '$elemMatch': {
        'name': 'test1'
      }
    }
  };
Atlas atlas-b8d6l3-shard-0 [primary] test> db.filter.find( filter, projection)
[
  {
    _id: ObjectId("6440e61fd80fa2295ca82d76"),
    array: [ { userId: ObjectId("6440e6a3d80fa2295ca82d77"), name: 'test1' } ]
  }
]

Additionally, you can also use aggregation for similar desired output.

L:et us know if you have further queries.

Regards
Aasawari