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

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements