Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get all fields names in a MongoDB collection?
To get all field names in a MongoDB collection, you can use Map-Reduce with the distinct() method. This approach extracts all unique field names across all documents in the collection.
Syntax
db.runCommand({
"mapreduce": "collectionName",
"map": function() {
for (var key in this) { emit(key, null); }
},
"reduce": function(key, values) { return null; },
"out": "temp_collection"
});
db.temp_collection.distinct("_id");
Sample Data
Let us create a collection with sample documents ?
db.getAllFieldNamesDemo.insertMany([
{"StudentFirstName": "David", "StudentAge": 23},
{"StudentFirstName": "John", "StudentAge": 25, "StudentCity": "New York"},
{"StudentLastName": "Miller", "StudentAge": 22, "StudentGrade": "A"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd998e9b50a6c6dd317ad90"),
ObjectId("5cd998e9b50a6c6dd317ad91"),
ObjectId("5cd998e9b50a6c6dd317ad92")
]
}
Display Sample Documents
db.getAllFieldNamesDemo.find();
{ "_id": ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName": "David", "StudentAge": 23 }
{ "_id": ObjectId("5cd998e9b50a6c6dd317ad91"), "StudentFirstName": "John", "StudentAge": 25, "StudentCity": "New York" }
{ "_id": ObjectId("5cd998e9b50a6c6dd317ad92"), "StudentLastName": "Miller", "StudentAge": 22, "StudentGrade": "A" }
Get All Field Names Using Map-Reduce
myMapReduce = db.runCommand({
"mapreduce": "getAllFieldNamesDemo",
"map": function() {
for (var myKey in this) { emit(myKey, null); }
},
"reduce": function(myKey, values) { return null; },
"out": "getAllFieldNamesDemo_keys"
});
db[myMapReduce.result].distinct("_id");
{
"result": "getAllFieldNamesDemo_keys",
"timeMillis": 1375,
"counts": {
"input": 3,
"emit": 9,
"reduce": 0,
"output": 6
},
"ok": 1
}
["StudentAge", "StudentCity", "StudentFirstName", "StudentGrade", "StudentLastName", "_id"]
How It Works
- The map function iterates through each field in every document and emits the field name as a key.
- The reduce function is not needed here, so it returns null.
- The result is stored in a temporary collection specified by the
"out"parameter. -
distinct("_id")extracts all unique field names from the temporary collection.
Conclusion
Map-Reduce with distinct() effectively extracts all unique field names from a MongoDB collection. This method works across all documents and captures every field that exists in the collection.
Advertisements
