In this post we will find out Is there an easy way to convert ISO 8601 duration to a time delta and for the same we can use an aggregation framework and $convert operator to convert an ISO 8601 duration to a time delta in MongoDB.
ISO 8601 Duration To Time
As ISO 8601 duration is a stander format to represent the duration or total time that is defined in the ISO 8601 standard. And here we will get to know how we can simply convert it into a time delta. And for the same, we have given an example below to get to know it better.
As we know that this duration can not be understood by human easily so we need to convert it into some understandable form so here we have used it as to covert into time.
db.collection.aggregate([ { $addFields: { timeDelta: { $convert: { input: { $substr: [ "$duration", 2, { $strLenCP: "$duration" } ] }, to: "long", onError: 0 } } } } ])
And here there are some terminology or name of databases and tables which are directed as followed.
- The collection is the name of the MongoDB collection which we have used in the above code.
- Duration is the name of the field that contains the ISO 8601 duration string which in a standard format.
- Date time is the name of the new field that will contain the converted time delta.
In this Aggregation of Pipeline used where $add field stage is used to add a new field which is the time delta to each and every document that exists in the collection. The use of $sub String operator is to extract the duration string by the document, from starting at the second character. The $strlnCP operator is used to determine the length of the duration string.
The $convert operator is used to convert the duration string to a time delta. The input parameter is set to the duration string, and then a parameter is set to ‘long’ which converts the duration string to milliseconds. The on error parameter is set to 0 which returns 0 if the conversion fails.
Note that the $ add field stage adds the time delta field to each document in the collection. If you want to update an existing field with the converted time delta, you can use the $set operator instead of $add field.
To learn more about Is there an easy way to convert ISO 8601 duration to time delta visit: by stack over flow.
To learn more about MongoDB Solutions and Tutorials along with the concepts of MongoDB and learn through the best visit: MongoDB Problems And Tutorials.