![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ]
Advertisements