Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"
      }
    }
  }
])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading