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 all the column names in a table in MongoDB
In MongoDB, there is no concept of columns since MongoDB is schema-less and does not contain tables. It contains the concept of collections and a collection has different types of documents with varying field structures.
Syntax
// Insert documents with different field structures
db.collectionName.insertOne({"fieldName1": "value1", "fieldName2": "value2"});
// Get all field names from a single document
db.collectionName.findOne();
// Get all documents to see different field structures
db.collectionName.find();
Sample Data
Let us create a collection with documents having different field structures ?
db.collectionOnDifferentDocumentDemo.insertMany([
{"UserName": "Larry"},
{"UserName": "David", "UserAge": 24},
{"UserName": "Carol", "UserAge": 25, "UserCountryName": "US"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c953b98749816a0ce933682"),
ObjectId("5c953ba4749816a0ce933683"),
ObjectId("5c953bb8749816a0ce933684")
]
}
Method 1: Get All Field Names Using find()
Display all documents to see the different field structures across the collection ?
db.collectionOnDifferentDocumentDemo.find();
{ "_id": ObjectId("5c953b98749816a0ce933682"), "UserName": "Larry" }
{ "_id": ObjectId("5c953ba4749816a0ce933683"), "UserName": "David", "UserAge": 24 }
{ "_id": ObjectId("5c953bb8749816a0ce933684"), "UserName": "Carol", "UserAge": 25, "UserCountryName": "US" }
Method 2: Get Field Names from Single Document
Use findOne() to see the field structure of the first document ?
db.collectionOnDifferentDocumentDemo.findOne();
{ "_id": ObjectId("5c953b98749816a0ce933682"), "UserName": "Larry" }
Key Points
- MongoDB collections can have documents with different field structures.
- Use
find()to see all field variations across documents. - Use
findOne()to examine a single document's field structure.
Conclusion
MongoDB's schema-less nature allows documents in the same collection to have different fields. Use find() or findOne() to explore the field structures present in your collection documents.
Advertisements
