MongoDB Aggregation Framework
We’ll perform various aggregation operations using MongoDB’s aggregation framework
Update documents with aggregation pipeline: multiply ‘age’ field by 2 and store in ‘doubleAge’ field
db.users.aggregate([
{ $addFields: { doubleAge: { $multiply: ["$age", 2] } } },
{ $out: "users" }
])
Count the number of documents in ‘users’ collection
db.users.aggregate([
{ $count: "total_users" }
])
Group documents in ‘users’ collection by ‘age’ and calculate the count in each group
db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
Perform a left outer join between ‘posts’ and ‘users’ collections based on ‘author’ field
db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "author",
foreignField: "username",
as: "author_info"
}
}
])
Get the first document in each group sorted by ‘age’ in descending order in ‘users’ collection
db.users.aggregate([
{ $sort: { age: -1 } },
{ $group: { _id: null, oldestUser: { $first: "$$ROOT" } } }
])
Perform map-reduce operation to calculate the total age of all users
var mapFunction = function () {
emit("totalAge", this.age);
};
var reduceFunction = function (key, values) {
return Array.sum(values);
};
db.users.mapReduce(
mapFunction,
reduceFunction,
{ out: { inline: 1 } }
);
We use various stages such as $addFields, $out, $count, $group, $lookup, $first, and map-reduce for different aggregation operations.
Aggregation framework allows us to perform complex computations, transformations, and data analysis on MongoDB collections efficiently.
MongoDB Cheat Sheet
MongoDB is a document-oriented NoSQL database that revolutionizes data storage with its flexibility and scalability. By storing data in JSON-like documents, MongoDB offers developers a powerful and intuitive way to handle complex data structures. From basic CRUD operations to advanced aggregation techniques, MongoDB empowers users to build robust and dynamic applications with ease.
In this MongoDB cheat sheet, we’ll delve into MongoDB’s key concepts, including data types, CRUD operations, query techniques, aggregation framework, indexing strategies, transaction support, and data modeling approaches. Each section is packed with examples and explanations to help you grasp MongoDB’s functionalities quickly and efficiently.