Understanding MongoDB requires familiarity with its fundamental concepts. This section covers the key elements that form the foundation of MongoDB’s document-oriented model.
Documents are the basic unit of data in MongoDB. They are similar to rows in relational databases but are more flexible.
Example Document:
{
"_id": ObjectId("5099803df3f4948bd2f98391"),
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"interests": ["reading", "cycling", "photography"]
}
Collections are groups of documents, analogous to tables in relational databases. Unlike tables, collections do not enforce a schema.
Creating a Collection:
db.createCollection("users")
A MongoDB server can host multiple databases, each containing its own set of collections.
Switching to a Database:
use myDatabase
BSON (Binary JSON) is the binary-encoded serialization of JSON-like documents used by MongoDB. It extends JSON with additional types like Date and Binary data.
_id
FieldEvery MongoDB document requires a unique _id
field that acts as a primary key. If not provided, MongoDB automatically generates an ObjectId for this field.
The MongoDB Shell is an interactive JavaScript interface to MongoDB, useful for querying and manipulating data as well as performing administrative operations.
Starting the MongoDB Shell:
mongo
Indexes in MongoDB are similar to indexes in relational databases. They improve the speed of data retrieval operations.
Creating an Index:
db.users.createIndex({ "username": 1 })
MongoDB’s aggregation framework is based on the concept of data processing pipelines, allowing for complex data transformations and analyses.
Simple Aggregation Example:
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$product", total: { $sum: "$amount" } } }
])
Understanding these concepts forms the foundation for effectively working with MongoDB and leveraging its features in your applications. In the next sections, we’ll explore how to perform various operations using these concepts.