Mongo
Basics
Database Operations
Query Operators
Aggregation Pipeline Stages
Examples
Creating a database
Creating a collection
db.createCollection('students');
Inserting documents into a collection
db.students.insertOne({name: 'John Doe', age: 21, gender: 'M'});
db.students.insertMany([
{name: 'Jane Doe', age: 19, gender: 'F'},
{name: 'Bob Smith', age: 22, gender: 'M'}
]);
Updating documents in a collection
db.students.updateOne({name: 'John Doe'}, {$set: {age: 23}});
db.students.updateMany({gender: 'M'}, {$inc: {age: 1}});
Deleting documents from a collection
db.students.deleteOne({name: 'Bob Smith'});
db.students.deleteMany({gender: 'F'});
Finding documents in a collection
db.students.find();
db.students.find({gender: 'M'});
db.students.findOne({name: 'John Doe'});
Querying with operators
db.students.find({age: {$gt: 20}});
db.students.find({name: {$regex: /Doe/i}});
Sorting results
db.students.find().sort({age: -1});
Limiting results
db.students.find().limit(2);
Aggregating data
db.students.aggregate([
{$group: {_id: '$gender', avg_age: {$avg: '$age'}}}
]);
Indexing collections for faster queries
db.students.createIndex({name: 1});
Joining collections with $lookup
db.students.aggregate([
{
$lookup: {
from: 'grades',
localField: '_id',
foreignField: 'student_id',
as: 'grades'
}
}
]);