- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 names of all keys in the MongoDB collection?
The syntax to get names of all keys in the collection is as follows:
var yourVariableName1=db.yourCollectionName.findOne(); for(var yourVariableName 2 in yourVariableName1) { print(yourVariableName); }
To understand the above syntax, let us create a collection with documents. The collection name we are creating is “studentGetKeysDemo”.
The following is the query to create documents:
>db.studentGetKeysDemo.insert({"StudentId":1,"StudentName":"Larry","StudentAge":23,"StudentAddress":"US", ... "StudentHobby":["Cricket","Football","ReadingNovel"], "StudentMathMarks":89,"StudentDOB":ISODate('1998-04-06')});
The following is the output:
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method. The query is as follows:
> db.studentGetKeysDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6c12dd68174aae23f5ef5f"), "StudentId" : 1, "StudentName" : "Larry", "StudentAge" : 23, "StudentAddress" : "US", "StudentHobby" : [ "Cricket", "Football", "Reading Novel" ], "StudentMathMarks" : 89, "StudentDOB" : ISODate("1998-04-06T00:00:00Z") }
Here is the query to get names of all keys from the collection “studentGetKeysDemo”:
> var allKeys=db.studentGetKeysDemo.findOne(); > for(var myKey in allKeys){print(myKey);}
The following is the output displaying all the keys:
_id StudentId StudentName StudentAge StudentAddress StudentHobby StudentMathMarks StudentDOB
- Related Articles
- Get all fields names in a MongoDB collection?
- Get all the column names in a table in MongoDB
- Get a collection of keys in the StringDictionary in C#
- Get all embedded documents with “isMarried” status in a MongoDB collection
- Get the maximum element in MongoDB collection?
- Get the size of a collection in MongoDB using conditions?
- Deleting all records of a collection in MongoDB Shell?
- Get the count of the number of documents in a MongoDB Collection?
- Shortest Path to Get All Keys in C++
- Get execution stats in MongoDB for a collection
- Filter documents in MongoDB if all keys exist as fields?
- Get the top most document from a MongoDB collection
- How to get the child of a MongoDB collection by the key?
- How to delete all the documents from a collection in MongoDB?
- MongoDB aggregate to get the count of field values of corresponding duplicate names?

Advertisements