Get value of a specific field using aggregation in MongoDB

My document:

[
  {
    "_id": "5f969419d40c1580f2d4aa36",
    "users": {
      "foo@bar.com": "baz",
      "foo2@bar.com": "baz2"
    }
  },
  {
    "_id": "5f9694d4d40c1580f2d4aa38",
    "users": {
      "baz@test.com": "foo"
    }
  }
]

If i use this aggregate, i get two users. Ok. But how can i get only the value of "foo@bar.com"?
Test in https://mongoplayground.net/p/3kW2Rw6fSjh

db.collection.aggregate([
  {
    "$project": {
      "users": {
        "$objectToArray": "$users"
      }
    }
  },
  {
    "$match": {
      "users.k": "foo@bar.com"
    }
  },
  {
    "$project": {
      "users": {
        "$arrayToObject": "$users"
      }
    }
  }
])

>Solution :

You can add a $filter stage after the $match stage:

{
    $set: {
      users: {
        $filter: {
          input: "$users",
          cond: {
            $eq: [
              "$$this.k",
              "foo2@bar.com"
            ]
          }
        }
      }
    }
  },

See how it works on the playground example

Leave a Reply