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 ?
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, ....
} }
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With