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 all distinct keys of a nested object

I have following data in my collection:

[
    {
        _id: "2313123123",
        metadata: {
            path: "...",
            value: "...",
            name: "..."
        }
    },
    {
        _id: "2313123123",
        metadata: {
            path: "...",
            name: "...",
            origin: "...",
        }
    },
    {
        _id: "2313123123",
        metadata: {
            path: "...",
            source: "..."
        }
    },
]

I want to retrieve all distinct key names of the field metadata from my documents.
I want to retrieve ["path", "value", "name", "origin", "source"].

How can I query for this? Is this possible with the distinct method or do I need to use aggregate?

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’ll have to use an aggregate for this, sadly due to the nature of your needs this is going to be a very "expensive" pipeline to execute. There is no way to avoid iterating over the entire collection and adding the unique keys to the array.

We’re going to use $objectToArray to turn metadata into an array, then $unwind it and finally using $group we could save all the unique values.

db.collection.aggregate([
  {
    $project: {
      keys: {
        $map: {
          input: {
            "$objectToArray": "$metadata"
          },
          in: "$$this.k"
        }
      }
    }
  },
  {
    $unwind: "$keys"
  },
  {
    $group: {
      _id: null,
      keys: {
        "$addToSet": "$keys"
      }
    }
  }
])

Mongo Playground

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