Projecting single element from array - MongoDB

Viewed 24

I'm working on retrieving selective data from an array based on certain conditions. But I don't to unwind it. Is there any way in mongoDB to project a single element in array of objects which matches a condition.

1 Answers

The positional operator $ would be perfect here, from the docs:

The positional $ operator limits the contents of an to return the first element that matches the query condition on the array.

For input in the structure:

[
  {
    "arr": [
      {
        value: "other value"
      },
      {
        value: "match this"
      },
      {
        value: "dont match"
      }
    ]
  }
]

You just use this query:

db.collection.find({
  "arr.value": "match this"
},
{
  "arr.$": 1
})

Output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "arr": [
      {
        "value": "match this"
      }
    ]
  }
]

Mongo Playground

Related