0
0
MongoDBquery~30 mins

Type conversion expressions ($toInt, $toString) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using $toInt and $toString in MongoDB Aggregation
📖 Scenario: You work at a small online store. The product prices are stored as strings in the database, but you need to calculate total prices as numbers for reports.
🎯 Goal: Build a MongoDB aggregation pipeline that converts price strings to integers using $toInt and then converts the total back to a string using $toString.
📋 What You'll Learn
Create a collection named products with documents containing name and price as strings.
Add a variable to hold the conversion target type.
Use $toInt to convert the price field to an integer.
Use $toString to convert the total price back to a string.
💡 Why This Matters
🌍 Real World
Many databases store numbers as strings for flexibility, but calculations require numeric types. Using $toInt and $toString helps convert data types during aggregation for accurate reports.
💼 Career
Data analysts and backend developers often need to convert data types in MongoDB to prepare data for calculations, reporting, and data cleaning.
Progress0 / 4 steps
1
Create the products collection with price strings
Create a collection called products with these exact documents: { name: "Pen", price: "10" }, { name: "Notebook", price: "25" }, and { name: "Eraser", price: "5" }.
MongoDB
Need a hint?

Use insertMany to add multiple documents to the products collection.

2
Add a variable for the target type conversion
Create a variable called targetType and set it to the string "int" to represent the integer conversion target.
MongoDB
Need a hint?

Use const targetType = "int" to define the type for conversion.

3
Convert the price field to integer using $toInt
Write an aggregation pipeline that uses $addFields to add a new field priceInt which converts the price string to an integer using $toInt.
MongoDB
Need a hint?

Use $addFields to add priceInt and convert price with $toInt.

4
Convert the total price back to string using $toString
Extend the aggregation pipeline by adding a $group stage to sum all priceInt values into totalPrice, then add a $project stage to convert totalPrice to a string field called totalPriceString using $toString.
MongoDB
Need a hint?

Use $group to sum priceInt and $project to convert the sum to string with $toString.