MongoDB Basic Operations Commands

Introduction

MongoDB is a NoSQL database designed for flexible data modeling and scalability. It allows for dynamic schemas, enabling developers to store and retrieve data efficiently. At its core, MongoDB relies on a set of commands to interact with the database, manage collections, and query documents. These commands form the foundation of working with MongoDB, offering essential tools for data manipulation and retrieval. Understanding these commands is crucial for effective database management and application development.

Core Commands

MongoDB provides a rich set of commands to perform essential operations. Below are the key commands for beginners:

1. db

The db command is used to interact with a specific database. For example:

db

This outputs the current database name.

2. insert

The insert command adds new documents to a collection. Example:

db.collection.insert({ name: "Alice", age: 30 });

This creates a new document in the collection with the specified fields.

3. update

The update command modifies existing documents. Example:

db.collection.updateOne({ name: "Alice" }, { $set: { age: 31 } });

This updates the age of the document where name is "Alice".

4. delete

The delete command removes documents from a collection. Example:

db.collection.deleteOne({ name: "Alice" });

This deletes the document where name is "Alice".

5. find

The find command retrieves documents from a collection. Example:

db.collection.find().limit(10);

This returns the first 10 documents in the collection.

6. count

The count command returns the number of documents in a collection. Example:

db.collection.countDocuments({});

This counts all documents in the collection.

Data Modeling

MongoDB emphasizes flexibility in data modeling. Key commands help structure data effectively:

1. createCollection

Creates a new collection. Example:

db.createCollection("users");

This initializes a new collection named users.

2. insert

Adds documents to a collection. Example:

db.users.insert({ name: "Alice", email: "alice@example.com" });

This inserts a new user document into the users collection.

3. createIndex

Creates an index for faster queries. Example:

db.users.createIndex({ name: 1 }, { unique: true });

This creates a unique index on the name field of the users collection.

Querying

MongoDB's querying capabilities are powerful, with commands for filtering, sorting, and aggregating data. Key commands include:

1. find

Retrieves documents based on criteria. Example:

db.users.find({ age: { $gt: 25 } });

This finds users older than 25.

2. findAndModify

Modifies and retrieves documents in a single operation. Example:

db.users.findAndModify({ query: { name: "Alice" }, update: { $inc: { age: 1 } } });

This increments the age of the document where name is "Alice".

3. countDocuments

Returns the number of documents matching a query. Example:

db.users.countDocuments({ age: { $gt: 25 } });

This counts users older than 25.

4. aggregate

Executes complex queries using pipelines. Example:

db.users.aggregate([
  { $match: { age: { $gt: 25 } } },
  { $sort: { age: -1 } }
]);

This returns users older than 25 sorted by age descending.

Advanced Commands

While the core commands cover basic operations, advanced commands offer more functionality:

1. mapReduce

Performs aggregation using map and reduce functions. Example:

db.users.mapReduce(
  "function() { emit(this.name, this.age) }",
  "function (arr) { return { total: _.sum(arr.map(function(e) { return e.age; })), avg: _.avg(arr.map(function(e) { return e.age; })) } }",
  { out: "aggregation" }
);

This calculates the total and average age of users.

2. drop

Deletes all documents from a collection. Example:

db.users.drop();

This removes all documents from the users collection.

3. validate

Checks if a document adheres to a schema. Example:

db.users.validate({ name: "string", age: "int" });

This validates the name and age fields of documents.

By mastering these commands, developers can efficiently manage and query MongoDB data, ensuring flexibility and performance in their applications.