To insert data into a MongoDB collection, you can use the insertOne()
or insertMany()
methods.
insertOne()
: Inserts a single document into a collection.Example:javascriptCopy codedb.users.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" });
insertMany()
: Inserts multiple documents into a collection.Example:javascriptCopy codedb.users.insertMany([ { name: "Jane Doe", age: 25, email: "jane.doe@example.com" }, { name: "Alice Smith", age: 28, email: "alice.smith@example.com" } ]);
MongoDB provides the find()
method to query documents from a collection. You can use various query operators to filter results, sort data, and limit the number of documents returned.
find()
: Retrieves documents from a collection.Example:javascriptCopy codedb.users.find();
This will return all documents in the users
collection.find()
with Query: You can specify a query to filter documents.Example (find users who are 30 years old):javascriptCopy codedb.users.find({ age: 30 });
find()
with Projection: You can specify which fields to include or exclude in the result.Example (find users and only return their name
and age
):javascriptCopy codedb.users.find({}, { name: 1, age: 1 });
findOne()
: Retrieves a single document that matches a query.Example:javascriptCopy codedb.users.findOne({ email: "john.doe@example.com" });
countDocuments()
: Counts the number of documents in a collection that match a query.Example:javascriptCopy codedb.users.countDocuments({ age: { $gt: 20 } });
MongoDB provides several methods to update documents, including updateOne()
, updateMany()
, and replaceOne()
.
updateOne()
: Updates the first document that matches a query.Example (update a user’s age):javascriptCopy codedb.users.updateOne( { name: "John Doe" }, // Query filter { $set: { age: 31 } } // Update operation );
updateMany()
: Updates all documents that match a query.Example (increase age for all users above 25):javascriptCopy codedb.users.updateMany( { age: { $gt: 25 } }, { $inc: { age: 1 } } // Increment the age by 1 );
replaceOne()
: Replaces the entire document that matches a query.Example (replace the document for John Doe):javascriptCopy codedb.users.replaceOne( { name: "John Doe" }, { name: "John Doe", age: 32, email: "john.doe@newemail.com" } );
MongoDB supports various operators for updating documents. Some commonly used operators are:
$set
: Sets the value of a field.$inc
: Increments the value of a field.$push
: Adds an item to an array.$pull
: Removes an item from an array.$rename
: Renames a field.MongoDB provides the deleteOne()
and deleteMany()
methods for deleting documents from a collection.
deleteOne()
: Deletes the first document that matches the query.Example (delete a user by email):javascriptCopy codedb.users.deleteOne({ email: "john.doe@example.com" });
deleteMany()
: Deletes all documents that match the query.Example (delete all users under 20 years old):javascriptCopy codedb.users.deleteMany({ age: { $lt: 20 } });
drop()
: Deletes an entire collection (all documents and indexes).Example (drop the users
collection):javascriptCopy codedb.users.drop();
You can sort query results in ascending or descending order by using the sort()
method.
db.users.find().sort({ age: 1 }); // 1 for ascending, -1 for descending
db.users.find().limit(5);
You can retrieve distinct values from a specific field using the distinct()
method.
distinct()
: Returns an array of distinct values for a field.Example (get all distinct ages from the users
collection):javascriptCopy codedb.users.distinct("age");
Indexes can be created to improve the speed of search operations.
email
field):javascriptCopy codedb.users.createIndex({ email: 1 });
db.users.getIndexes();
MongoDB’s aggregation framework allows you to process and analyze data in complex ways. It supports operations like filtering, grouping, sorting, and joining data.
db.users.aggregate([ { $group: { _id: "$age", count: { $sum: 1 } } } ]);
$match
, $group
, $sort
, $project
) to transform data.Example:javascriptCopy codedb.users.aggregate([ { $match: { age: { $gte: 18 } } }, { $group: { _id: "$age", totalUsers: { $sum: 1 } } }, { $sort: { totalUsers: -1 } } ]);
MongoDB’s basic operations include powerful methods for creating, reading, updating, and deleting documents. These CRUD operations can be combined with advanced features like sorting, limiting results, aggregations, and indexing to build flexible and efficient applications. The flexibility of MongoDB’s document-based model and its rich querying capabilities make it a great choice for managing modern, dynamic data.