'MongoDB type a attribute of document in collection
I am currently working on a project that save regulary data to a MongoDB database. In this database I have a several element and each document contains date.
Problematic
The documents contains wrong type for date attribute.
It's due of bad inserting, all documents have a date in string format.
I can per one update each attribute with MongoDB Atlas graphical interface, but this solution is too long..
Question
I wanted to know if in MongoDB we have a solution to update the type of an attribute in all documents in a collection.
Solution 1:[1]
For your case, the simplest solution is using $toDate in an update with aggregation pipeline
db.collection.update({},
[
{
"$addFields": {
"date": {
"$toDate": "$date"
}
}
}
])
Here is the Mongo playground for your reference.
If you need to cater with other date format, you can use $dateFromString.
db.collection.update({},
[
{
"$addFields": {
"date": {
"$dateFromString": {
"dateString": "$date",
"format": <your format here>
}
}
}
}
])
You can refer to this official documentation on $dateFromString regarding the format parser.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ray |
