mongoDB 在 aggregate 中使用$dateToString 格式化字符串时间戳出现好坑的问题,求助各位哥哥姐姐

2017-12-08 15:56:35 +08:00
 threedream

最近使用 mongoDB 存储了大量的用户登录记录,文档结构如下:

{
  "_id" : ObjectId("5a1fde257756dca1c86f2d23"),
  "_class" : "com.aaa.LoginHistory",
  "uid" : "94989242",
  "ip" : "192.168.1.219",
  "imei" : "865736037366641",
  "epid" : "33189023-9472-4f30-81cf-8c7d13132aae5",
  "platform" : "Android",
  "timestamp" : "1512037117100",
  "address" : "中国,江苏省,南京市,建邺区"
}
db.loginHistory.aggregate([
	{$match:{"timestamp":{"$lte":"1513412162000","$gte":"1512548162000"}}},
    {$group:{_id:"$uid"}}
])

因此出现了很大的问题:

最后经过各种百度找到了一种实现:

db.loginHistory.aggregate(
    [
        {
            $match:{
                timestamp:{
                    $lte:"1513399696240",
                    $gte:"1513389696240"
                }
            }
        },
        {
            $project:{
                uid:1,
                timestamp:1,
                _id:0
            }
        },
        {
            $group:{
                _id:{
                    uid:"$uid",
                    date:{
                        $dateToString:{
                            format:"%Y-%m-%d",
                            date:{
                                $add:[new Date(0),parseInt("$timestamp")]
                            }
                        }
                    }
                }
            }
        },
        {
            $group:{
                _id:{
                    date:"$_id.date"
                },
                count:{"$sum":1}
            }
        }
    ]
)

但是问题又来了,执行报错:

assert: command failed: {
    "ok" : 0,
    "errmsg" : "$dateToString is only defined on year 0-9999, tried to use year 292278994",
    "code" : 18537
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:287:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5

百思不得其解,尝试性的把 parseInt("$timestamp")改成 parseInt("1513399696240"),执行得到结果:

{ "_id" : { "date" : "2017-12-16" }, "count" : 19 }

。。。。。。。。。。。。。求助各位大哥

10736 次点击
所在节点    MongoDB
1 条回复
rails3
2017-12-08 16:03:54 +08:00
map reduce 可以解决

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/413132

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX