- In MongoDB, type conversion-related aggregation functions are essential when dealing with diverse data types in collections. These functions enable converting data from one type to another within aggregation pipelines, ensuring proper data processing and manipulation.
- Here are the main type conversion functions:
$convert
- The $convert operator is used to convert a value to a specified type. It provides control over the type conversion, including handling of invalid inputs or null values.
- Syntax:
{
$convert: {
input: <expression>,
to: <type>,
onError: <expression>, // Optional
onNull: <expression> // Optional
}
}
- input: The expression or field to be converted.
- to: The target data type (e.g., string, int, bool, etc.).
- onError: The value returned if the conversion fails.
- onNull: The value returned if the input is null.
- Example: Imagine a collection employees where some age are stored as strings, and you need to convert them to integers.
db.employees.insertMany([
{
"_id": 1,
"name": "Alice",
"age": "25",
"salary": "50000.75",
"isEmployed": "true",
"joinDate": "2023-01-15T10:00:00Z",
"bigNumber": "9223372036854775807",
"objectRef": "60e0ef48f0a8b22d08d3ef7b"
},
{
"_id": 2,
"name": "Bob",
"age": 30,
"salary": 60000.50,
"isEmployed": false,
"joinDate": "2022-07-10T09:00:00Z",
"bigNumber": "123456789123456789",
"objectRef": "60e0ef48f0a8b22d08d3ef7c"
},
{
"_id": 3,
"name": "Charlie",
"age": "35",
"salary": "70000",
"isEmployed": "false",
"joinDate": "2021-04-12T08:30:00Z",
"bigNumber": "18446744073709551615",
"objectRef": "60e0ef48f0a8b22d08d3ef7d"
}
])
- Query:
db.employees.aggregate([{
$project: {
name: 1, priceInt: {
$convert: {
input: "$age", to: "int", onError: 0, onNull: null
}
}
}
}])
// Output
[
{ _id: 1, name: 'Alice', priceInt: 25 },
{ _id: 2, name: 'Bob', priceInt: 30 },
{ _id: 3, name: 'Charlie', priceInt: 35 }
]
$toString
- This function converts a value to a string.
db.employees.aggregate([
{
$project: {
name: 1,
salary: { $toString: "$salary" }
}
}
])
// Output
[
{ _id: 1, name: 'Alice', salary: '50000.75' },
{ _id: 2, name: 'Bob', salary: '60000.5' },
{ _id: 3, name: 'Charlie', salary: '70000' }
]
$toInt
- Converts a value to an integer.
db.employees.aggregate([
{
$project: {
name: 1,
age: { $toInt: "$age" }
}
}
])
// Output
[
{ _id: 1, name: 'Alice', age: 25 },
{ _id: 2, name: 'Bob', age: 30 },
{ _id: 3, name: 'Charlie', age: 35 }
]
$toBool
- This converts a value to a boolean (true or false). string always consider as true.
db.employees.aggregate([
{
$project: {
name: 1,
isEmployed: { $toBool: "$isEmployed" }
}
}
])
// Output
[
{ _id: 1, name: 'Alice', isEmployed: true },
{ _id: 2, name: 'Bob', isEmployed: false },
{ _id: 3, name: 'Charlie', isEmployed: true }
]
$toDouble
- This function converts a value to a double-precision floating-point number.
db.employees.aggregate([
{
$project: {
name: 1,
salary: { $toDouble: "$salary" }
}
}
])
// Output
[
{ _id: 1, name: 'Alice', salary: 50000.75 },
{ _id: 2, name: 'Bob', salary: 60000.5 },
{ _id: 3, name: 'Charlie', salary: 70000 }
]
$toDate
- Converts a value to a date.
db.employees.aggregate([
{
$project: {
name: 1,
joinDate: { $toDate: "$joinDate" }
}
}
])
// Output
[
{
_id: 1,
name: 'Alice',
joinDate: ISODate('2023-01-15T10:00:00.000Z')
},
{
_id: 2,
name: 'Bob',
joinDate: ISODate('2022-07-10T09:00:00.000Z')
},
{
_id: 3,
name: 'Charlie',
joinDate: ISODate('2021-04-12T08:30:00.000Z')
}
]
$toObjectId
- Convert a string representation of an ObjectId to a valid ObjectId.
db.employees.aggregate([
{
$project: {
name: 1,
objectRef: { $toObjectId: "$objectRef" }
}
}
])
// Output
[
{
_id: 1,
name: 'Alice',
objectRef: ObjectId('60e0ef48f0a8b22d08d3ef7b')
},
{
_id: 2,
name: 'Bob',
objectRef: ObjectId('60e0ef48f0a8b22d08d3ef7c')
},
{
_id: 3,
name: 'Charlie',
objectRef: ObjectId('60e0ef48f0a8b22d08d3ef7d')
}
]
$toDecimal
- The $toDecimal operator converts a value to a Decimal128 type. This is useful for high-precision decimal numbers that can't be accurately represented by the double data type.
- Convert a string representation of a high-precision number to a Decimal128.
db.employees.aggregate([
{
$project: {
name: 1,
bigNumber: { $toDecimal: "$bigNumber" }
}
}
])
// Output
[
{
_id: 1,
name: 'Alice',
bigNumber: Decimal128('9223372036854775807')
},
{
_id: 2,
name: 'Bob',
bigNumber: Decimal128('123456789123456789')
},
{
_id: 3,
name: 'Charlie',
bigNumber: Decimal128('18446744073709551615')
}
]
- This ensures that the high precision of the number is preserved during calculations, which is essential for financial applications.
$toLong
- The $toLong operator converts a value to a long type, which is a 64-bit integer. It is useful for handling larger integer values that go beyond the range of standard 32-bit integers.
db.employees.aggregate([{
$project: {
name: 1,
anyNumber: {
$toLong: "54512121212"
}
}
}])
// Output
[
{ _id: 1, name: 'Alice', anyNumber: Long('54512121212') },
{ _id: 2, name: 'Bob', anyNumber: Long('54512121212') },
{ _id: 3, name: 'Charlie', anyNumber: Long('54512121212') }
]
- This type is particularly useful for handling very large numbers, such as identifiers, timestamps, or big integer values in applications.
$type
- While $type is not strictly a conversion function, it is an operator that allows you to identify the current type of a field, which can be useful before performing type conversions.
- Let's say you want to check the type of a field before deciding on a conversion or operation.
db.employees.aggregate([{
$project: {
name: 1,
salaryValueType: {
$type: "$salary"
}
}
}])
// Output
[
{ _id: 1, name: 'Alice', salaryValueType: 'string' },
{ _id: 2, name: 'Bob', salaryValueType: 'double' },
{ _id: 3, name: 'Charlie', salaryValueType: 'string' }
]
- The $type operator returns the type of the field (e.g., string, int, array, object), allowing you to handle different types dynamically within the aggregation pipeline.
$isNumber
- This operator is used to determine whether a value is of a numeric type (int, long, double, or decimal).
- Let's say you're unsure if a value is numeric and you want to filter only numeric fields.
db.employees.aggregate([{
$project: {
name: 1,
salaryIsNumber: {
$isNumber: "$salary"
}
}
}])
// Output
[
{ _id: 1, name: 'Alice', salaryIsNumber: false },
{ _id: 2, name: 'Bob', salaryIsNumber: true },
{ _id: 3, name: 'Charlie', salaryIsNumber: false }
]
- This operator can be particularly useful when filtering documents to ensure you're only working with numeric fields.
Conclusion
- Type conversion functions in MongoDB provide flexibility and ease in transforming data types within the aggregation framework. They help handle diverse data formats and ensure accurate processing of information, especially when data types are inconsistent or require transformation for calculations, sorting, or filtering.
No comments:
Post a Comment