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
Migrate URLs in Next.js
How to migrate URLs in Next.js to avoid 404 errors and improve SEO with permanent redirects.
Inject HTML content into an Astro component
While working on a project within the Astro framework, I encountered a scenario where I needed to fill HTML content within a script tag.
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.
Featured Posts
Introducing new blog about OAuth, OpenID Connect, and IAM Solutions
I'm excited to announce the launch of a new blog named CerberAuth, where I'll be exploring the world of OAuth, OpenID Connect, and IAM solutions for modern security.
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.