Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Converting string to date in MongoDB?
To convert the string to date in MongoDB, use the $dateFromString operator within an aggregation pipeline. This operator parses a string and converts it to a proper date object.
Syntax
db.yourCollectionName.aggregate([
{
$project: {
anyVariableName: {
$dateFromString: {
dateString: '$yourFieldName'
}
}
}
}
]);
Sample Data
Let us create a collection with some documents to understand the string to date conversion ?
db.ConvertStringToDateDemo.insertMany([
{"ArrivalDate": "20-10-2019"},
{"ArrivalDate": "21-02-2019"},
{"ArrivalDate": "10-12-2018"},
{"ArrivalDate": "31-01-2017"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5c6ef3596fd07954a489069f"),
ObjectId("5c6ef3616fd07954a48906a0"),
ObjectId("5c6ef36d6fd07954a48906a1"),
ObjectId("5c6ef37b6fd07954a48906a2")
]
}
Display all documents from the collection ?
db.ConvertStringToDateDemo.find().pretty();
{
"_id" : ObjectId("5c6ef3596fd07954a489069f"),
"ArrivalDate" : "20-10-2019"
}
{
"_id" : ObjectId("5c6ef3616fd07954a48906a0"),
"ArrivalDate" : "21-02-2019"
}
{
"_id" : ObjectId("5c6ef36d6fd07954a48906a1"),
"ArrivalDate" : "10-12-2018"
}
{
"_id" : ObjectId("5c6ef37b6fd07954a48906a2"),
"ArrivalDate" : "31-01-2017"
}
Example: Converting String to Date
Here is the query to convert string to date using $dateFromString ?
db.ConvertStringToDateDemo.aggregate([
{
$project: {
StringToDate: {
$dateFromString: {
dateString: '$ArrivalDate'
}
}
}
}
]);
{
"_id" : ObjectId("5c6ef3596fd07954a489069f"),
"StringToDate" : ISODate("2019-10-20T00:00:00Z")
}
{
"_id" : ObjectId("5c6ef3616fd07954a48906a0"),
"StringToDate" : ISODate("2019-02-21T00:00:00Z")
}
{
"_id" : ObjectId("5c6ef36d6fd07954a48906a1"),
"StringToDate" : ISODate("2018-12-10T00:00:00Z")
}
{
"_id" : ObjectId("5c6ef37b6fd07954a48906a2"),
"StringToDate" : ISODate("2017-01-31T00:00:00Z")
}
Key Points
- The
$dateFromStringoperator automatically parses common date formats - Use this operator within the
$projectstage of aggregation pipeline - The result is an ISODate object that can be used for date operations
Conclusion
Use $dateFromString within an aggregation pipeline to convert string representations of dates into proper date objects. This enables date−based queries and operations on your MongoDB documents.
Advertisements
