8

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 ?

1 Answer 1

19

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, ....
    } }
])
Sign up to request clarification or add additional context in comments.

4 Comments

@chridam - can we have mix of find and aggregate.. i have to use find query as well.. is that possible?
Yes, you can include queries with your aggregate operation by using the $match pipeline step. Read more with examples here.
Is it there a chance to do this without $project? Because I don't want to project all the fields from an entry..they are about 40 which is a lot.
@Tenzolinho You can use $addFields like in the above edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.