Get all fields names in a MongoDB collection?


You can use the concept of Map Reduce. Let us first create a collection with documents −

> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.getAllFieldNamesDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }

Following is the query to get all fields names in a MongoDB collection −

> myMapReduce = db.runCommand({
   "mapreduce" : "getAllFieldNamesDemo",
   "map" : function() {
      for (var myKey in this) { emit(myKey, null); }
   },
   "reduce" : function(myKey, s) { return null; },
   "out": "getAllFieldNamesDemo" + "_k"
})
{
   "result" : "getAllFieldNamesDemo_k",
   "timeMillis" : 1375,
   "counts" : {
      "input" : 1,
      "emit" : 3,
      "reduce" : 0,
      "output" : 3
   },
   "ok" : 1
}
> db[myMapReduce.result].distinct("_id");

This will produce the following output displaying the filed names −

[ "StudentAge", "StudentFirstName", "_id" ]

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements