How to get ALL field names in a MongoDB collection including nested field names using mongo shell?

Viewed 768

I was searching a way to retrieve all possible fields in a MongoDB collection given the fact that in the totality of all documents, not every single one has the same fields in an attempt to be prepared for all possible cases in the task I got at hand.

I found this useful question/answer to be able to retrieve all fields. The answer is useful but as stated in a comment there, is also possible to get all nested field names too? This question alone requires another question thus, I'd like to know how to do it.

Here's what I mean:

total: 15861
ref_code: "0FMjZj"
settings: Object
    pa_rejected: "1"
    pa_redeem: "1"
    new: "1"

In this simplified example, using Mongo CLI with the solution shared in the quoted answer I get:

[
   "total",
   "ref_code",
   "settings"
]

Is there a way to also get pa_rejected, pa_redeem and new somehow?

1 Answers

Apply the map function recursively to the document:

db['foo'].deleteMany({})
db['foo'].insert({a:{foo:{bar:{zoom:42}}},b:'c',d:'e',x:[]})

mr = db.runCommand({
  "mapreduce" : "foo",
  "map" : function() {
    var f = function() {
      for (var key in this) {
        if (this.hasOwnProperty(key)) {
          emit(key, null)
          if (typeof this[key] == 'object') {
            f.call(this[key])
          }
        }
      }
    }
    f.call(this);
  },
  "reduce" : function(key, stuff) { return null; },
  "out": "myCollectionName" + "_keys"
})


print(db[mr.result].distinct("_id"))
Related