MongoDB将日期转换为字符串 [英] MongoDB converting date to string

查看:797
本文介绍了MongoDB将日期转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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

详细信息:

文档:

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

查询:

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

错误:

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 ?

推荐答案

您不能使用聚合框架一起使用https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/"rel =" nofollow noreferrer> $addFields

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:

使用 $addFields :

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

或使用 $project

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

这篇关于MongoDB将日期转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆