-1

I want to use this mongoDB collection:

[
  {
    "_id": {
      "$oid": "627c4eb87e7c2b8ba510ac4c"
    },
    "Contact": [
      {
        "name": "ABC",
        "phone": 5501234,
        "mail": "abc@mail.com"
      },
      {
        "name": "DEF",
        "phone": 6001234,
        "mail": "def@mail.com"
      }
    ],
    "nomatter": "trash"
  }
]

search for {"name":"ABC"} and return only {"mail":"abc@mail.com"}.

It's possible to use find or it's necessary to use aggregate?

Mingut
  • 71
  • 6
  • 1
    Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – ray May 12 '22 at 23:21
  • Unfortunately not. All return a full json. I just wanted the fragment. But thanks for help! – Mingut May 13 '22 at 00:48
  • 1
    What did you try? – Wernfried Domscheit May 13 '22 at 06:28

1 Answers1

1

Try this one:

db.collection.aggregate([
  { $match: { "Contact.name": "ABC" } },
  {
    $project: {
      Contact: {
        $filter: {
          input: "$Contact",
          cond: { $eq: [ "$$this.name", "ABC" ] }
        }
      }
    }
  },
  { "$replaceWith": { mail: { $first: "$Contact.mail" } } }
])

Mongo Playground

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
  • WoW, that's Amazing! I had never thought of using replaceWith to move up the hierarchy. So simple, but not found in other similar answers. – Mingut May 13 '22 at 16:57