如何通过 mongo 处理客户端印度时间和美国时间服务器日期之间的日期

How to handle date between India Time on Client side and Server date in US Time via mongo

我有一个应用程序,其客户位置将在印度。我的应用程序必须根据客户端提供的日期范围聚合数据。因此,如果客户提供 2016 年 12 月 14 日至 2016 年 12 月 21 日。它应该从 2016 年 12 月 14 日 00:00:00am 到 2016 年 12 月 21 日 23:59:59pm 进行搜索。 现在,一旦我将我的日期发送到我的服务器,它就会转换为
Dec 13 2016 18:30:00 GMT+0000 (UTC)
Dec 21 2016 18:29:59 GMT+0000 (UTC)
现在我将聚合查询写为

let cursor = Trip.aggregate([{
        $match: {
            startTime: {
                $gte: startDate.toDate(),
                $lte: endDate.toDate()
            },
        }
    },{
        $group: {
            _id: {
                date: {
                    $dayOfMonth: "$startTime"
                },
                month: {
                    $month: "$startTime"
                },
                year: {
                    $year: "$startTime"
                }
            },
            count: {
                $sum: 1
            }
        }
    }]);

这导致以下输出

[ { _id: { date: 17, month: 12, year: 2016 }, count: 2 },
  { _id: { date: 16, month: 12, year: 2016 }, count: 2 },
  { _id: { date: 13, month: 12, year: 2016 }, count: 2 } ]

旅行实际发生的时间是

"startTime" : ISODate("2016-12-13T20:10:20.381Z")
"startTime" : ISODate("2016-12-13T19:54:56.855Z")

实际发生在 14-12-2016 01:40:20am14-12-2016 01:24:56am

我希望所有的东西都在一个时间范围内,但是 MongoDB 不允许在 UTC 以外的任何其他时间范围内存储数据,并且在客户端查询中管理不同的时间变得越来越困难和数据库。 我该如何解决?

您可以通过以下方式进行。您可以使用偏移毫秒保存记录。因此,您的 collection 将如下所示。

{
    "_id": ObjectId("585a97dcaceaaa5d2254aeb5"),
    "start_date": ISODate("2016-12-17T00:00:00Z"),
    "offsetmillis": -19080000
} {
    "_id": ObjectId("585a97dcaceaaa5d2254aeb6"),
    "start_date": ISODate("2016-11-17T00:00:00Z"),
    "offsetmillis": -19080000
} {
    "_id": ObjectId("585a97dcaceaaa5d2254aeb7"),
    "start_date": ISODate("2016-11-13T00:00:00Z"),
    "offsetmillis": -19080000
}

并且您可以更新聚合查询以在处理时包含偏移毫秒。

aggregate([{
    $match: {
        start_date: {
            $gte: new ISODate("2016-01-01"),
            $lte: new ISODate("2016-12-31")
        },
    }
}, {
    $group: {
        _id: {
            date: {
                $dayOfMonth: {
                    $add: ["$start_date", "$offsetmillis"]
                }
            },
            month: {
                $month: {
                    $add: ["$start_date", "$offsetmillis"]
                }
            },
            year: {
                $year: {
                    $add: ["$start_date", "$offsetmillis"]
                }
            }
        },
        count: {
            $sum: 1
        }
    }
}]);

示例响应

{ "_id" : { "date" : 12, "month" : 11, "year" : 2016 }, "count" : 1 }
{ "_id" : { "date" : 16, "month" : 11, "year" : 2016 }, "count" : 1 }
{ "_id" : { "date" : 16, "month" : 12, "year" : 2016 }, "count" : 1 }

你可以进一步优化它,但我认为这会给你一个想法。