Open In App

What is a collection in MongoDB?

Last Updated : 26 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).

In this article, we will learn about the collection in MongoDB. We will also learn about document storage, schema-less nature, namespace, dynamic creation, indexing, and CRUD operations on the collection.

Collections in MongoDB

The database is used to store related information. SQL stores data in tables, while MongoDB stores information in collections. A database can have one or many collections, and each collection must have a unique name. Collections store information about objects or entities, such as cars. For example, a collection can store different models and their related features in the form of documents. Documents are similar to rows/records in SQL tables and store data in BSON format. A collection can have any number of documents, each with a unique ID and data.

Features of collection

  • Schema-less nature: Collections in MongoDB don't apply a schema due to which documents in the same collection can have different structures, providing flexibility to the collection.
  • Indexing: Indexing on collection increases the query processing by scanning the documents that satisfy the indexed field .
  • Scalability : We can handle extensive data volume and high traffic load efficiently using the Sharded Collection.

Namespace

Namespace is a combination of the database name and the collection name or view name with a dot as a separator. The maximum possible length of the namespace is 255 bytes .It is represented as "database-name. collection-name".

CRUD operation

We can perform the basic Create, Read, Update and Delete Operations on Collections in MongoDB.

Create Collection

use db_name;
db.createCollection("collection_name")
const studentsData = [
{ rollno: 101, Name: "Raj ", favSub: "Math" },
{ rollno: 102, Name: "Yash", favSub: "Science" },
{ rollno: 103, Name: "Jay", favSub: "History" },
];
db.collection_name.insertMany( studentsData );
  • Initially we specify the database that is going to be used.
  • createCollection method is used to create a collection. The argument of the method specifies the name of the collection.
  • As the collection is created we can insert a document using insertOne() method and many documents using the insertMany() method.

Read From the Collection

db.collection_name.find({})

find() method is used to along with empty {} are used to read all the documents in the collection

Example:

use Geeks;
db.createCollection("student");

// insert into collection
db.student.insertMany([ { rollNo : 101 ,name:"Ronny",favSub : "Maths" }, {rollNo : 102 ,name:"Yash",favSub : "History"} ]);

// Read document from collection
db.student.find();
Collections-in-MongoDb
Collections in MongoDb

In the above example ,Geeks database is used to store the student Collection.Two documents are inserted into the collection using the insertMany() method.The inserted documents are read using find() method.

Update Operation

To update the documents we can use updateOne() or updateMany methods.

Syntax:

db.collection_name.update(   query,    update,    optional)
  • query is used to filter out the documents which are to be updated
  • update is to update the values of the fields int the document.
  • optional parameter contains the upsert ,multi, writeConcern, collation, arrayFilters field which are use according to conditions.

Delete Documents from the Collection

The delete operation are used to delete or remove the documents from a collection. You can perform delete operations using the deleteOne() method and deleteMany() method

db.collection_name.deleteMany(  condtion  );

Example: Update the favSub field of rollNo 102;

 db.student.updateOne({ rollNo: 102 }, { $set: { favSub: "Cloud Computing" } });
Update-Collection
Update Collection

Indexing on Collection

Index is created on the collection to enhance the performance of the query i.e. fetching the data in a short span of time without iterating over the whole dataset. Indexes make searching in a collection easier with the limited number of documents. Binary tree data structure is used as an index. In documents, the _id field is a default index which is automatically created by MongoDB and we are not allowed to drop this index.. The indexes are order by the value of the field specified in the index. createIndex() method is used to create the index and getIndexes() method is used to fetch the indexes on collection.

Syntax:

db.<collection>.createIndex( { <field>: “text”} )

Example:

db.student.createIndex({ rollNo: 1 });
db.student.getIndexes()
Indexing-in-Collection
Indexing in Collection

In the above example we create a custom index on student collection using the createIndex() method.The createIndex method is passed with the rollNo field to create a index on it.When we use getIndexes() method it return 2 index , _id and rollNo as _id is the default index .


Next Article
Article Tags :

Similar Reads