Nearby lessons

19 of 22

🔤 MongoDB: Type Conversion and Checking Operators

MongoDB provides several type conversion and type checking operators to transform field data types and verify data formats inside aggregation pipelines. These operators are extremely useful when working with inconsistent or mixed-type data.

📚 Sample Collection Setup

MongoDB Shell
NoSQL
Database
1db.studentsArr.insertMany([
2 { _id: 1, name: "Alice", scores: [85, 92, 88, 76, 95], tags: ["js", "py", "mongo"] },
3 { _id: 2, name: "Bob", scores: [70, 65, 88], tags: ["java", "c#"] },
4 { _id: 3, name: "Cara", scores: [100, 99, 98], tags: ["go", "rust"] }
5]);
Query Result
JSON Output
✅ 3 student documents inserted successfully.

1️⃣ Using $toString — Convert to String

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 scoresString: { $toString: "$scores" } // Converts array to string
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "scoresString": "[85, 92, 88, 76, 95]" }

2️⃣ Using $toInt — Convert to Integer

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 firstScoreInt: { $toInt: { $arrayElemAt: ["$scores", 0] } }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "firstScoreInt": 85 }

3️⃣ Using $toLong — Convert to 64-bit Integer

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 totalAsLong: { $toLong: { $sum: "$scores" } }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "totalAsLong": NumberLong(436) }

4️⃣ Using $toDouble — Convert to Floating-Point

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 avgAsDouble: { $toDouble: { $avg: "$scores" } }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "avgAsDouble": 87.2 }

5️⃣ Using $toDecimal — Convert to Decimal128

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 preciseValue: { $toDecimal: { $multiply: ["$scores.0", 1.1] } }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "preciseValue": NumberDecimal("93.5") }

6️⃣ Using $toBool — Convert to Boolean

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 hasScores: { $toBool: "$scores" }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "hasScores": true }

7️⃣ Using $toDate — Convert to Date

MongoDB Shell
NoSQL
Database
1db.dates.aggregate([
2 { $project: {
3 eventDate: { $toDate: "$dateStr" }
4 }}
5]);
Query Result
JSON Output
{ "eventDate": ISODate("2023-01-01T00:00:00Z") }

8️⃣ Using $toObjectId — Convert to ObjectId

MongoDB Shell
NoSQL
Database
1db.users.aggregate([
2 { $project: {
3 userId: { $toObjectId: "$hexId" }
4 }}
5]);
Query Result
JSON Output
✅ Converts valid 12-byte hex string to ObjectId.

9️⃣ Using $convert — Safe Type Conversion

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 safeConversion: {
5 $convert: {
6 input: { $arrayElemAt: ["$tags", 0] },
7 to: "int",
8 onError: "Invalid",
9 onNull: null
10 }
11 }
12 }}
13]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "safeConversion": "Invalid" }

🔟 Using $type — Check BSON Type

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 scoresType: { $type: "$scores" }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "scoresType": "array" }

1️⃣1️⃣ Using $isNumber — Numeric Check

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 isNumeric: { $isNumber: { $avg: "$scores" } }
5 }}
6]);
Query Result
JSON Output
{ "_id": 1, "name": "Alice", "isNumeric": true }
Keep Going!MongoDB - Conditional Operators