Introduction to MongoDB Collections

In MongoDB, data is organized into collections, which are similar to tables in relational databases. Collections are used to store related documents, and MongoDB provides a flexible schema that allows you to work with data in various ways. This guide covers the basic CRUD operations (Create, Read, Update, Delete) you can perform on MongoDB collections.


Step 1: Launch the MongoDB Shell

Ensure you have MongoDB installed and the server running. Open your terminal or command prompt and launch the MongoDB shell by typing:


mongo

Step 2: Select a Database

Choose the database you want to work with using the

use
command:


use myDatabase

Step 3: Basic CRUD Operations

Let's explore the basic CRUD operations you can perform on a MongoDB collection.


Create: Insert Documents

To create documents in a collection, use the

insertOne
or
insertMany
method. For example:


db.myCollection.insertOne({
name: "John Doe",
age: 30
})
db.myCollection.insertMany([
{ name: "Alice Smith", age: 25 },
{ name: "Bob Johnson", age: 35 }
])

Read: Query Documents

Use the

find
method to read documents. To retrieve all documents in a collection:


db.myCollection.find()

Update: Modify Documents

To update documents, use the

updateOne
or
updateMany
method. For example, update a document's age:


db.myCollection.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
)

Delete: Remove Documents

To delete documents, use the

deleteOne
or
deleteMany
method. For instance, delete a document by name:


db.myCollection.deleteOne({ name: "John Doe" })

Conclusion

MongoDB collections allow you to store and manage your data effectively. By mastering the basic CRUD operations, you can create, retrieve, update, and delete documents as needed. As you gain experience with MongoDB, you can explore more advanced features for working with collections.