Skip to main content

Collections

In MongoDB, collections are used to group MongoDB documents. They are quite similar to tables in relational databases, but unlike SQL table rows, different documents in a MongoDB collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.

What is a Collection?

A collection holds one or more documents. While each database can have multiple collections, a collection belongs to a single database. A document within a collection in MongoDB can be compared to a row within a table in relational databases.

Creating Collections

In MongoDB, you don't necessarily need to create collections. MongoDB creates collections automatically when you insert some documents. The following example shows how you can create a collection named "users":

db.createCollection("users")

However, you can also create a collection while inserting a document in it, as shown below:

db.users.insertOne({
name: 'John Doe',
email: '[email protected]'
})

In this case, if the 'users' collection did not already exist, MongoDB would create it.

Inserting Documents

You can insert documents into a collection using the insertOne() method for a single document or insertMany() for multiple documents. Here's an example of inserting a single document:

db.users.insertOne({
name: 'Jane Doe',
email: '[email protected]'
})

And here's an example of inserting multiple documents:

db.users.insertMany([{
name: 'Alice',
email: '[email protected]'
}, {
name: 'Bob',
email: '[email protected]'
}])

Reading Documents

You can read documents from a collection using the find() method. If you want to find all documents in a collection, you can use find() without any arguments:

db.users.find()

If you want to find a specific document, you can provide a query object:

db.users.find({ name: 'John Doe' })

Updating Documents

You can update documents using the updateOne() method or updateMany() method. Here's an example:

db.users.updateOne({ name: 'John Doe' }, { $set: { email: '[email protected]' } })

This will update the email of the first document that matches the query.

Deleting Documents

To delete documents, you can use the deleteOne() or deleteMany() methods. Here's an example:

db.users.deleteOne({ name: 'John Doe' })

This will delete the first document that matches the query.

Conclusion

In this tutorial, you have learned about MongoDB collections, how to create them, and how to perform basic CRUD (Create, Read, Update, and Delete) operations on them. As you continue exploring MongoDB, you'll find that collections are a fundamental part of working with this database.