In this step, we'll explore various techniques to format and transform output using MongoDB's aggregation pipeline. We'll continue working with our bookstore database.
Let's start by launching the MongoDB shell:
mongosh
Switch to the bookstore database:
use bookstore
First, let's use $toUpper
and $toLower
to format text fields:
db.books.aggregate([
{
$project: {
_id: 0,
titleUpperCase: { $toUpper: "$title" },
authorLowerCase: { $toLower: "$author" }
}
}
]);
Example output:
[
{
titleUpperCase: 'MONGODB BASICS',
authorLowerCase: 'jane smith'
},
// ... other book documents
]
Next, let's format numeric values using $round
and create formatted price strings:
db.books.aggregate([
{
$project: {
_id: 0,
title: 1,
roundedPrice: { $round: ["$price", 1] },
formattedPrice: {
$concat: ["$", { $toString: { $round: ["$price", 2] } }]
}
}
}
]);
Example output:
[
{
title: 'MongoDB Basics',
roundedPrice: 30,
formattedPrice: '$29.99'
},
// ... other book documents
]
We can also format arrays and create complex string representations:
db.books.aggregate([
{
$project: {
_id: 0,
title: 1,
categoriesSummary: {
$reduce: {
input: "$categories",
initialValue: "",
in: {
$concat: [
"$$value",
{ $cond: [{ $eq: ["$$value", ""] }, "", ", "] },
"$$this"
]
}
}
}
}
}
]);
Example output:
[
{
title: 'MongoDB Basics',
categoriesSummary: 'Database, Programming'
},
// ... other book documents
]
This last example uses $reduce
to join array elements into a comma-separated string.