MongoDB is a NoSQL database that uses a document-oriented data model. It stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time.
- Data Model: Uses
documents and collectionsinstead of tables and rows. - Schema:
Schema-less, allowing dynamic changes to the structure of documents. - Scalability: Designed for
horizontal scalingthrough sharding. - Query Language: Uses a
rich, JSON-basedquery language.
MongoDB is schema-less, meaning you don't need to define a rigid structure for your documents upfront. You can add or remove fields as needed.
A document is a set of key-value pairs, similar to JSON objects. Each document is a record in a collection and can have different fields and structures compared to other documents in the same collection.
A collection is a grouping of MongoDB documents. Collections are similar to tables in relational databases but without a fixed schema. Documents within a collection can have different fields.
The _id field is a unique identifier for each document in a MongoDB collection. It ensures that each document can be uniquely identified and retrieved. By default, MongoDB creates an ObjectId as the value for the _id field if it's not provided by the user.
You can insert a document into a MongoDB collection using the insertOne or insertMany methods.
db.collectionName.insertOne({
name: "John Doe",
age: 30,
occupation: "Software Developer"
});| Index Type | Description | Code Example |
|---|---|---|
| Single-field index | Creates an index on a single field of a document. Useful for sorting and querying based on that field. | db.collection.createIndex({ fieldName: 1 }) |
| Compound index | Creates an index on multiple fields of a document. Improves query performance for complex queries involving multiple fields. | db.collection.createIndex({ field1: 1, field2: -1 }) |
| Text index | Creates an index on text content within a document. Enables full-text search and querying based on text content. | db.collection.createIndex({ fieldName: "text" }) |
| Geospatial index | Creates an index for geographical data (points, lines, polygons). Optimizes queries based on location. | db.collection.createIndex({ location: "2dsphere" }) |
| Hashed index | Creates a hashed index on a single field. Useful for evenly distributing data across buckets. | db.collection.createIndex({ fieldName: "hashed" }) |
| TTL index | Automatically expires documents after a specified time. Useful for managing time-sensitive data. | db.collection.createIndex({ expirationDate: 1 }, { expireAfterSeconds: 3600 }) |
//create an index
db.collectionName.createIndex({ name: 1 });Indexes are data structures that improve query performance by creating an ordered list of values for one or more fields. They help MongoDB find specific documents more efficiently.