0

query:

    mongo_date_formatter = {
        "$addFields": {
            "Date": {
                "$dateFromString": {
                    "dateString": "$Date",
                    "format": "%d-%m-%Y"
                }
            }
        }
    }

date format in database:

"Date": "2018-04-15"

error i am getting:

    OperationFailure at /api/data/
    unknown operator: $dateFromString

version on local system:

    MongoDB shell version v4.0.9

version in server:

    3.2.0

i tried with:

    mongo_date_formatter = {
        "$addFields": {
            "Date": {
                "$dateToString": {
                    "date": "$Date",
                    "format": "%Y-%m-%d"
                }
            }
        }
    }

This . it is not working.

I thing it is the problem with the server . is there any way to fix it?

Please have a look.

  • Could you please share your complete query along with your DB schema and desired result as "$dateToString" used with aggregation. – Jitendra Apr 23 '19 at 08:42

2 Answers2

0

if you check the Mongo docs they specify that $dateFromString operator was added at version 3.6.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
0

Try this query as below :

MongoDB server version: 3.6

db.collection.aggregate([
    {
        $project: {
            "properDate": {                  // Converting string to Proper date format
                $dateFromString: { 
                    dateString: '$Date',
                } 
            },

        } 
    },
    {
        $project: {
            "FormatedDate": { $dateToString: { format: "%Y-%m-%d", date: "$properDate" } },
        }
    }
])
Jitendra
  • 3,135
  • 2
  • 26
  • 42
  • 2
    Bro. I am using 3.2.0 version – soubhagya pradhan Apr 23 '19 at 09:03
  • Still searching for a solution. Please wait. – Jitendra Apr 23 '19 at 09:05
  • https://stackoverflow.com/questions/55807798/pymongo-date-formatting-issue-while-fetching-data-between-two-dates – soubhagya pradhan Apr 23 '19 at 09:08
  • PLease have a look. i have added the question again. – soubhagya pradhan Apr 23 '19 at 09:08
  • Using MongoDB versions >= 2.6 and < 3.2 MongoDB does not have the native operators that do the conversion, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents. Withing the loop, convert the field to an ISODate object and then update the field using the $set operator, as in your case the field Date currently holds the date in string format. – Jitendra Apr 23 '19 at 09:27
  • Read that post and try to follow the same steps. https://stackoverflow.com/questions/10942931/converting-string-to-date-in-mongodb – Jitendra Apr 23 '19 at 09:29