Skip to content
Advertisement

How to get keys of nested mongodb documents

I have data like this, I need all the keys from this mongodb collection like property1,property2 etc.

{
    "_id": 0,
    "config": [{
            "property1":"a",
            "property2": "b",
            "property3": "c",
            "property4": "d"
        },
        {
            "property1": "a",
            "property2": "bb",
            "property3": "cc",
            "property4": "d",
            "ispropert5": true
        },
        {
            "property1": "a",
            "property2": "b",
            "property3": "c",
            "property4": "ddd",
            "ispropert5": false,
            "ispropert6": false
        }
    ],
    "entity": "123asdf",
    "url": "",
    "createdDate": 1
}

I tried

db.COLLECTION_NAME.find({},{config:1}).forEach(function(doc){Object.keys(doc).forEach(function(key){innerkeys[key]=1})}):

Advertisement

Answer

You can use $objectToArray to read object keys dynamically and then run $reduce with $concatArrays to merge the results:

db.collection.aggregate([
  {
    $project: {
      properties: {
        $reduce: {
          input: "$config",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              {
                $map: {
                  input: {
                    $objectToArray: "$$this"
                  },
                  in: "$$this.k"
                }
              }
            ]
          }
        }
      }
    }
  }
])

Output:

[
  {
    "_id": 0,
    "properties": [
      "property3",
      "property4",
      "property1",
      "property2",
      "property4",
      "ispropert5",
      "property1",
      "property2",
      "property3",
      "property2",
      "property3",
      "property4",
      "ispropert5",
      "ispropert6",
      "property1"
    ]
  }
]

Mongo playground

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement