使用投影来格式化日期和获取本地时间的MongoDB Shell脚本 [英] MongoDB shell script using projection to format date and get local time

查看:91
本文介绍了使用投影来格式化日期和获取本地时间的MongoDB Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的投影

db.MyCollection.aggregate([
    { "$match": { "ProjectID" : 999 } },
    { "$sort": { "CreatedDate": -1 } },
    {
        "$project": {
            "_id": 0,
            "DueDate": {
                "$dateToString": { 
                    "format": "%Y-%m-%d %H-%M", 
                    "date": "$DueDate"
                }
            }
        }
    }
])

我在Mongo中的到期日值是ISODate("2016-10-08T17:00:00.000Z"),在当地时间是22:30 PM,但是使用上面的投影,我得到的值是5:00 PM

My due date value in Mongo is ISODate("2016-10-08T17:00:00.000Z") which in local time is 22:30 PM but using above projection I get the value as 5:00 PM

ISODate("2016-10-08T17:00:00.000Z").toLocaleString()返回Saturday, October 08, 2016 22:30:00

那么我该如何在投影中应用toLocaleString()并以上述格式获取结果

So how can I apply toLocaleString() in projection and get the result in the above format

推荐答案

您不能直接使用"toLocaleString()".但是,您可以添加偏移量.

You can't directly use "toLocaleString()". However, you can add the offset.

1)第三个流水线用于添加偏移量

1) Third pipeline is used to add the offset

2)第四个管道用于格式化日期

2) Fourth pipeline is used to format the date

var tzOffset = 5.5 * 1000 * 60 * 60;

db.MyCollection.aggregate( [
   { "$match": { "ProjectID" : 999 } },
   { "$sort": { "CreatedDate": -1 } },
   {          
      $project: {
         localTime: {
            $let: {
               vars: {
                   "localTime": { "$add": [ "$DueDate", tzOffset]

                }
               },
               in: { $add: ["$$localTime"] }
            }
         }
      }
   },
   {          
      $project: {
         "_id": 0, 
         "formattedLocalTime": {
                "$dateToString": { 
                    "format": "%Y-%m-%d %H-%M", 
                    "date": "$localTime"
                }
            }
      }
   }

]);

输入:-

"DueDate" : ISODate("2016-08-11T10:17:09.203Z")
"DueDate" : ISODate("2016-08-11T23:16:09.203Z")

输出:-

"formattedLocalTime" : "2016-08-11 15-47"
"formattedLocalTime" : "2016-08-12 04-46"

请注意输出2.正确填写了下一个日期.

这篇关于使用投影来格式化日期和获取本地时间的MongoDB Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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