Last Updated: 30 May, 2023
In MongoDB, a collection is a group of documents stored in the database. It is the equivalent of a table in a relational database. Collections in MongoDB do not enforce a specific schema, which means that documents within a collection can have different structures.
Each document within a collection is stored as a JSON-like BSON (Binary JSON) object.
To create a collection in MongoDB, we can use the db.createCollection() method in the MongoDB shell or use a driver/library in our preferred programming language. Here's an example using the MongoDB shell:
use database_name db.createCollection("collection_name")
This will create a new collection named "collection_name" in the specified database.
We can also insert documents into a collection using the
db.collection_name.insertOne() or db.collection_name.insertMany() methods. For example, to insert a document into the "collection_name" collection, we can use the following command:
db.collection_name.insertOne({ "key": "value" })
Here, { "key": "value" } represents the document we want to insert.
Once we have created a collection and inserted documents, we can perform various operations on the collection, such as querying documents, updating documents, deleting documents, and more.
It's important to note that if we try to insert documents into a collection that doesn't exist, MongoDB will create the collection automatically when you insert the first document.
That's all, guys. I hope this MongoDB article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com