Get names of all keys in the collection



  • 3 Answer(s)

    You can do this one:

    mr = db.runCommand({
      "mapreduce" : "my_collection",
      "map" : function() {
        for (var key in this) { emit(key, null); }
      },
      "reduce" : function(key, stuff) { return null; },
      "out": "my_collection" + "_keys"
    })
    

    So we can run distinct on the resulting collection so as to find all the keys:

    db[mr.result].distinct("_id")
    ["foo", "bar", "baz", "_id", ...]
    

     

    Answered on December 24, 2018.
    Add Comment

    You can try this one:

    doc=db.thinks.findOne();
    for (key in doc) print(key);
    
    Answered on December 24, 2018.
    Add Comment

    Can you use in collabrate with new $objectToArrray in 3.4.4 version to convert all top key & value pair into document arrays followed by $unwind & $group with $addToSet to get distinct keys across entire collection.

    To your reference $$ROOT 

    db.things.aggregate([
      {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
      {"$unwind":"$arrayofkeyvalue"},
      {"$group":{"_id":null,"allkeys":{"$addToSet":"$arrayofkeyvalue.k"}}}
    ])
    

    can you use the following query for getting keys in a single document

    db.things.aggregate([
      {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
      {"$project":{"keys":"$arrayofkeyvalue.k"}}
    ])
    
    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.