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 attribute list from MongoDB object?
To get attribute list from MongoDB object, use a for...in loop to iterate through the document properties and extract each key and value along with their data types.
Syntax
var document = db.collection.findOne();
for (key in document) {
var value = document[key];
print(key + "(" + typeof(value) + "): " + value);
}
Create Sample Data
db.getAttributeListDemo.insertOne({
"StudentId": 101,
"StudentName": "John",
"StudentAdmissionDate": new ISODate('2019-01-12'),
"StudentSubjects": ["MongoDB", "Java", "MySQL"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cbdfcc9ac184d684e3fa269")
}
Display Document
db.getAttributeListDemo.find().pretty();
{
"_id": ObjectId("5cbdfcc9ac184d684e3fa269"),
"StudentId": 101,
"StudentName": "John",
"StudentAdmissionDate": ISODate("2019-01-12T00:00:00Z"),
"StudentSubjects": [
"MongoDB",
"Java",
"MySQL"
]
}
Extract Attribute List
var myDocument = db.getAttributeListDemo.findOne();
for (myKey in myDocument) {
var originalValue = myDocument[myKey];
print(myKey + "(" + typeof(originalValue) + "): " + originalValue);
}
_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
Key Points
- The
for...inloop iterates through all enumerable properties of the document -
typeof()returns the JavaScript data type of each field value - Arrays and dates appear as "object" type in the output
Conclusion
Use a for...in loop with findOne() to extract all document attributes, their data types, and values. This method provides a complete overview of the document structure and field types.
Advertisements
