Changing Document Field Types with MongoDB
Emmanuel Gautier / March 30, 2023
2 min read
MongoDB is a flexible and versatile database system that can handle a wide variety of data types. However, there are situations where you may need to change the data type of a document field during query execution. For example, you may want to convert a string field to a date field, or vice versa. Fortunately, MongoDB provides various aggregation operators, such as $convert
, that allow you to manipulate document field types during query execution.
The $convert
operator is a MongoDB aggregation pipeline stage that converts a value to a specified data type. It is useful when you want to convert a value in a document from one data type to another. This operator takes three parameters:
input
: The value to be convertedto
: The target data type to which the input value should be converted. Valid data types include "double", "string", "objectId", "bool", "date", "int", "long", "decimal", "timestamp", and "binary".onError
(optional): Specifies the behavior in case an error occurs during the conversion. Valid options are "error", "null", or "skip".onNull
(optional): Specifies the behavior in case of null value
More details and examples about the $convert
operator are available on the official MongoDB manual.
MongoDB $convert example
Here's an example usage of the $convert
operator to convert a string field to a date:
db.collection.aggregate([
{
$project: {
convertedDate: {
$convert: {
input: "$stringField",
to: "date",
onError: {
$concat:
[
"Could not convert ",
{ $toString: "$stringField" },
" to type integer."
]
},
onNull: null
}
}
}
}
])
In this example, we use the operator within a $project
stage to convert the stringField to a date and store the result in a new field called convertedDate.
Javascript MongoDB $convert Example
Here is the same example but with the JavaScript SDK:
const { MongoClient } = require('mongodb');
// Replace the connection string with your own.
const uri = 'mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('mydb');
const collection = database.collection('mycollection');
const pipeline = [
{
$project: {
convertedDate: {
$convert: {
input: '$stringField',
to: 'date',
onError: {
$concat:
[
'Could not convert ',
{ $toString: '$stringField' },
' to type integer.'
]
},
onNull: null
}
}
}
}
];
const result = await collection.aggregate(pipeline).toArray();
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
Consulting
If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.
Related Posts
Formatting Big Numbers in JavaScript
When working with large numerical values in JavaScript, it can be challenging to display them in a way that's easy to read and understand. In this blog post, we'll explore techniques for formatting big numbers in JavaScript with built-in methods.
How to use Chakra UI Button and Link components with NextJS Link
There is some glue to add to make Chakra UI and NextJS work together. The Chakra UI components do not generate the "a" tag by default for a link. Let's see how to use the Chakra button to generate links between pages.
Extends Express session SessionData type
Express Session allows to store a lot of different data. There is a Typescript type named `SessionData` which allow to know what contains a session but not the data you will defined after without defining them.
Featured Posts
How to deal with Docker Hub rate limit on AWS
Since 2020, DockerHub has been limited to only 200 container image pull requests per six hours. This article will help you to deal with this limitation on AWS.
How to enable Python type checking in VSCode
Python now has support for type hints. In this article, we will see how to enable better IntelliSense and type checking analysis in VSCode.
How to manage Internationalization with NextJS SSG
Staticaly generating a website with the NextJS framework in different languages is not so obvious.