What is a collection in MongoDB?
Last Updated :
26 Jun, 2024
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 MongoDbIn 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 CollectionIndexing 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 CollectionIn 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 .
Similar Reads
Capped Collections in MongoDB
Creating a capped collection in MongoDB involves using the createCollection() method to define a collection with a fixed size and a maximum number of documents. Capped collections automatically overwrite old documents when they reach their size limit, making them ideal for use cases like logging or
6 min read
How to List All Collections in the MongoDB Shell?
Managing collections is a fundamental task in MongoDB database administration. Knowing how to list all collections in the MongoDB shell is essential for understanding your database structure and managing your data effectively. In this article, we'll explore how to list all collections in the MongoDB
3 min read
How to Rename Collection in MongoDB?
Renaming collections in MongoDB is a straightforward operation that helps in maintaining and organizing databases efficiently. MongoDB provides the renameCollection command and the db.collection.renameCollection() method for changing collection names within the same database. In this article, We wil
4 min read
How to Add a Column in MongoDB Collection?
In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections. In this
4 min read
MongoDB - Drop Collection
In MongoDB, managing collections is a fundamental aspect of database operations. The MongoDB drop collection command allows us to permanently delete an entire collection along with its documents and indexes. By using the db.collection.drop() method is essential when we need to clear outdated data or
4 min read
What is MongoDB Atlas?
MongoDB Atlas is a fully-managed cloud database service provided by MongoDB, designed to simplify database management for developers. With MongoDB Atlas, we can automate complex database tasks like scaling, backups, and security while focusing on building modern applications. It supports deployment
7 min read
MongoDB â Create Collection
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Unlike relational databases, it does not require a predefined schema, allowing for dynamic and scalable data management. This flexibility makes MongoDB ideal for various applications, including big data, real-time analyti
5 min read
How to use TTL collections in MongoDB?
TTL (Time-To-Live) collections in MongoDB is a special collection where it allows automatic deletion of documents after a specified duration. This technique is used in managing temporary data, such as user sessions cache logsHow TTL WorksTTL Index: You create a TTL index on a date field in your coll
5 min read
What are Naming Conventions for MongoDB?
MongoDB is a popular NoSQL database management system known for its flexibility and scalability. One important aspect of MongoDB development is proper naming conventions. These conventions ensure consistency, clarity, and readability across databases and applications. In this article, We will learn
4 min read
Collection-Level Access Control in MongoDB
In modern database management, fine-grained access control is essential to meet the complex security requirements of organizations. MongoDB, a leading NoSQL database, offers robust mechanisms for managing permissions at various levels, including collection-level access control. This feature enables
4 min read