Get all the column names in a table in MongoDB

MongoDBDatabaseBig Data Analytics

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 to store items.

Let us see the syntax −

db.yourCollectionName.insertOne({“YourFieldName”:yourValue, “yourFieldName”:”yourValue”,.......N});

If you want a single record from a collection, you can use findOne() and in order to get all records from the collection, you can use find().

The syntax is as follows −

db.yourCollectionName.findOne(); //Get Single Record
db.yourCollectionName.find(); // Get All Record

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c953b98749816a0ce933682")
}
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"David","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c953ba4749816a0ce933683")
}
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Carol","UserAge":25,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c953bb8749816a0ce933684")
}

Display all documents from a collection with the help of find() method. As discussed above find(), it will return all records.

The query is as follows −

> db.collectionOnDifferentDocumentDemo.find();

The following is the output −

{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c953ba4749816a0ce933683"), "UserName" : "David", "UserAge" : 24 }
{ "_id" : ObjectId("5c953bb8749816a0ce933684"), "UserName" : "Carol", "UserAge" : 25, "UserCountryName" : "US" }

Display a single record from a collection with the help of the findOne() method. The query is as follows −

> db.collectionOnDifferentDocumentDemo.findOne();

The following is the output −

{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
raja
Published on 01-Apr-2019 12:38:41
Advertisements