Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB converting date to string

Tags:

mongodb

PROBLEM:

Error when get Y-m-d from "SentTimestamp" : ISODate("2015-12-23T22:20:15Z")

DETAILS :

document :

{
...
"SentTimestamp" : ISODate("2015-12-23T22:20:15Z")
...
}

query :

db.foo.find({}, {$dateToString: {format:"%Y-%m-%d", date:"$SentTimestamp"}})

Error :

Error: error: {
    "$err" : "Can't canonicalize query: BadValue >1 field in obj: { format: \"%Y-%m-%d\", date: \"$SentTimestamp\" }",
    "code" : 17287

Can somebody explain how can I convert date to string, what is wrong above ?

like image 318
user647314 Avatar asked Jan 18 '16 13:01

user647314


1 Answers

You cannot use the $dateToString operator with projection in the find() method. Instead, use it with the aggregation framework in the $addFields or $project pipeline phase to return documents that have the datetime field converted to string with the desired format, as in the following example:

Using $addFields:

db.foo.aggregate([
    { "$addFields": {
        "sentDateString": { 
            "$dateToString": { 
                "format": "%Y-%m-%d", 
                "date": "$SentTimestamp" 
            } 
        }
    } }
])

or using $project

db.foo.aggregate([
    { "$project": {
        "sentDateString": { 
            "$dateToString": { 
                    "format": "%Y-%m-%d", 
                    "date": "$SentTimestamp" 
            } 
        },
        "otherFields": 1, ....
    } }
])
like image 69
chridam Avatar answered Sep 25 '22 18:09

chridam