Commonly Used MongoDB Commands
MongoDB is one of the most popular NoSQL databases, known for its flexibility, scalability, and high performance. When working with…
mongodb commands
Commonly Used MongoDB Commands
MongoDB is one of the most popular NoSQL databases, known for its flexibility, scalability, and high performance. When working with MongoDB, a variety of commands are frequently used to manipulate and query data. This article overviews the most commonly used MongoDB commands, showcasing their functionality through practical examples.
Database and Collection Operations
The basic operations of databases and collections
//Drop Databases
db.dropDatabase()
//Creating Collection
db.createCollection("collection_name")
//Drop Collection
db.collection_name.drop()
//Check DB Stats
db.stats()
//Check Collection Stats
db.collection_name.stats()
//List Users In The Database
db.getUsers()
//Add A New User
db.createUser({
user: "Mohsin",
pwd: "abcde",
roles: [{ role: "readWrite", db: "database_name" }]
})
Insert Documents
//Insert One Document
db.collection_name.insertOne({ name: "Mohsin", age: 18})
//Insert Multiple Documents
db.collection_name.insertMany([
{ name: "Mohsin", age: 18},
{ name: "Abbas", age: 20}
])
Query Documents
//Find All Documents
db.collection_name.find()
//Find Documents With a Filter
db.collection_name.find({ age: 18})
//Find One Document
db.collection_name.findOne({ name: "Mohsin" })
//Count Documents
db.collection_name.countDocuments({ age: 18})
Update Documents
//Update a Single Document
db.collection_name.updateOne(
{ name: "Mohsin" }, // Filter
{ $set: { age: 30} } // Update
)
//Update Multiple Documents
db.collection_name.updateMany(
{ company: "albright" },
{ $set: { age: 20} }
)
//Replace A Document
db.collection_name.replaceOne(
{ name: "Mohsin" },
{ name: "Mamun", age: 18 }
)
Delete Documents
//Delete a Single Document
db.collection_name.deleteOne({ name: "Mohsin" })
//Delete Multiple Documents
db.collection_name.deleteMany({ age: 18})
Delete Documents
//Create an Index
db.collection_name.createIndex({ name: 1 }) // 1 for ascending, -1 for descending
//List all Indexes
db.collection_name.getIndexes()
//Drop an Indexes
db.collection_name.dropIndex("name")
$set , $unset , $rename :Mutate Documents
The $set operator is used to update specific fields in a document or add them if they don't already exist.
The $unset operator is used to remove a field from a document to clean up unnecessary data.
The $renamerename operator is used to rename fields in a document
//Updating Fields
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $set: { name: "John Doe", age: 30 } }
);
//Removing Fields
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $unset: { age: "" } }
);
//Renaming Fields
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $rename: { name: "fullName" } }
);
$inc , $mul , $min , $max , $currentDate :Mutate Numeric Documents
The $inc operator increments (or decrements) a numeric field by a specified value. It's useful for updating counts or scores.
The $mul operator multiplies the value of a field by a specified number.
The $min operator updates the field only if the specified value is smaller than the current value.
The $max operator updates the field only if the specified value is greater than the current value.
This $currentDate operator is useful when you want to set a field to the current date or timestamp.
//Incrementing Fields
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $inc: { score: 5 } }
);
//Multiplying a Field's Value
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $mul: { salary: 1.1 } }
);
// Updating with a Minimum Value
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $min: { age: 25 } }
);
// Updating with a Maximum Value
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $max: { age: 35 } }
);
// Setting a Field to the Current Date
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $currentDate: { updatedAt: true } }
);
$push , $pop , $pull , $addToSet:Array Manipulation Operators
The $push operator adds an element to an array field. If the array doesn't exist, it will be created.
The $pop operator removes either the first or last element from an array.
The $pull operator removes elements from an array that match a specific criterion.
The $addToSet operator adds an element to an array only if it doesn’t already exist. It ensures that the array contains only unique elements.
//Adding elements to an array
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $push: { tags: "mongodb" } }
);
//Removing last or frist element from an array. 1 or -1
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $pop: { tags: 1 } }
);
//Removing specific elements from an array
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $pull: { tags: "mongodb" } }
);
//Adding unique elements to an array
db.collection.updateOne(
{ _id: ObjectId("id") },
{ $addToSet: { tags: "mongodb" } }
);
$eq, $ne, $gt, $lt :Comparison Operators
MongoDB provides several operators to compare fields with values. These include $eq (equal), $ne (not equal), $gt (greater than), and $lt (less than).
// Find documents where age is equal to 30
db.collection.find({ age: { $eq: 30 } });
// Find documents where age is greater than 25
db.collection.find({ age: { $gt: 25 } });
// Find documents where age is less than 35
db.collection.find({ age: { $lt: 35 } });
$in , $nin :Array Value Matching
The $in operator matches documents where a field's value is in a specified array, while $nin does the opposite, matching documents where a field's value is not in a specified array.
// Find documents where age is in [25, 30, 35]
db.collection.find({ age: { $in: [25, 30, 35] } });
// Find documents where age is not in [25, 30, 35]
db.collection.find({ age: { $nin: [25, 30, 35] } });
$and , $or :Logical Operators
The $and operator matches documents that satisfy all conditions, while the $or operator matches documents that satisfy at least one of the conditions.
// Find documents where age > 25 and city is New York
db.collection.find({
$and: [{ age: { $gt: 25 } }, { city: "New York" }]
});
// Find documents where age < 20 or city is Los Angeles
db.collection.find({
$or: [{ age: { $lt: 20 } }, { city: "Los Angeles" }]
});
$match , $group, $project , $sort , $limit, $skip :Aggregation Operators
The $match operator is used to filter documents based on specified criteria. It's similar to the find() operation but used within the aggregation pipeline.
The $group operator is used to group documents by a specified field and perform aggregation operations such as counting, summing, or averaging the grouped values.
The $project operator is used to include, exclude, or modify fields in the output of the aggregation. It allows you to reshape documents and present only the necessary information.
The $sort operator is used to sort the documents based on one or more fields in ascending or descending order.
The $limit operator is used to restrict the number of documents returned by the aggregation query.
The $skip operator skips a specified number of documents. It's typically used in conjunction with $limit pagination.
//Filtering documents
db.collection.aggregate([
{ $match: { age: { $gt: 25 } } }
]);
//Grouping Documents
db.collection.aggregate([
{ $group: { _id: "$city", totalAge: { $sum: "$age" } } }
]);
// Selecting and Modifying Fields
db.collection.aggregate([
{ $project: { name: 1, age: 1, _id: 0 } }
]);
//Sorting Documents
db.collection.aggregate([
{ $sort: { age: -1 } }
]);
//Limiting Documents
db.collection.aggregate([
{ $limit: 5 }
]);
//Skipping Documents
db.collection.aggregate([
{ $skip: 10 }
]);
MongoDB offers a variety operators that can be used to filter, transform, and modify your data in powerful ways. By combining these operators, you can write complex queries and efficiently manage your documents.
메타데이터
- post_id
- ca1db49a6e4a
- slug
- commonly-used-mongodb-commands-ca1db49a6e4a
- url
- https://medium.com/@saimumislam27/commonly-used-mongodb-commands-ca1db49a6e4a
- canonical_url
- https://medium.com/@saimumislam27/commonly-used-mongodb-commands-ca1db49a6e4a
- author_url
- https://medium.com/@saimumislam27
- status
- ok
- fetched_at
- 2026-07-22 02:17:40