Get attribute list from MongoDB object?


To get attribute list from MongoDB object, you can use for loop to extract key and value for document. Let us create a collection with documents −

>db.getAttributeListDemo.insertOne({"StudentId":101,"StudentName":"John","StudentAdmissi
onDate":new ISODate('2019-01-12'),"StudentSUbjects":["MongoDB","Java","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdfcc9ac184d684e3fa269")
}

Display all documents from a collection with the help of find() method −

> db.getAttributeListDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cbdfcc9ac184d684e3fa269"),
   "StudentId" : 101,
   "StudentName" : "John",
   "StudentAdmissionDate" : ISODate("2019-01-12T00:00:00Z"),
   "StudentSUbjects" : [
      "MongoDB",
      "Java",
      "MySQL"
   ]
}

Following is the query to get attribute list from MongoDB object −

> var myDocument = db.getAttributeListDemo.findOne();
> for (myKey in myDocument) {
...    var originalValue = myDocument[myKey];
...    print(myKey + "(" + typeof(originalValue ) + "): " + originalValue ) };

This will produce the following output −

_id(object): 5cbdfcc9ac184d684e3fa269
StudentId(number): 101
StudentName(string): John
StudentAdmissionDate(object): Sat Jan 12 2019 05:30:00 GMT+0530 (India Standard Time)
StudentSUbjects(object): MongoDB,Java,MySQL

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

827 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements