基于unix时间戳的Mongodb聚合

前端之家收集整理的这篇文章主要介绍了基于unix时间戳的Mongodb聚合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用谷歌搜索了很多,但没有找到任何有用的解决方案……我想找到每日用户的总数.
我有一个名为session_log的集合,其中包含以下文档
  1. {
  2. "_id" : ObjectId("52c690955d3cdd831504ce30"),"SORTID" : NumberLong(1388744853),"PLAYERID" : 3,"LASTLOGIN" : NumberLong(1388744461),"ISLOGIN" : 1,"logoUT" : NumberLong(1388744853)
  3. }

我想从LASTLOGIN汇总…

这是我的查询

  1. db.session_log.aggregate(
  2. { $group : {
  3. _id: {
  4. LASTLOGIN : "$LASTLOGIN"
  5. },count: { $sum: 1 }
  6. }}
  7. );

但它是按每个登录时间聚合,而不是每天.任何帮助,将不胜感激

MongoDB 3.0及更新版本:
  1. db.session_log.aggregate([
  2. {
  3. "$group": {
  4. "_id": {
  5. "$dateToString": {
  6. "format": "%Y-%m-%d","date": {
  7. "$add": [
  8. new Date(0),{ "$multiply": [1000,"$LASTLOGIN"] }
  9. ]
  10. }
  11. }
  12. },"count": { "$sum": 1 }
  13. }
  14. }
  15. ])

您需要通过将值乘以1000将LASTLOGIN字段转换为毫秒时间戳

  1. { "$multiply": [1000,"$LASTLOGIN"] }

,然后转换为日期

  1. "$add": [
  2. new Date(0),"$LASTLOGIN"] }
  3. ]

这可以在$project管道中完成,方法是将您的毫秒时间添加到零毫秒Date(0)对象,然后从转换后的日期中提取$year,$month,$dayOfMonth个零件,然后您可以在$group管道中使用这些零件对文档进行分组到了白天.

因此,您应该将聚合管道更改为:

  1. var project = {
  2. "$project":{
  3. "_id": 0,"y": {
  4. "$year": {
  5. "$add": [
  6. new Date(0),"$LASTLOGIN"] }
  7. ]
  8. }
  9. },"m": {
  10. "$month": {
  11. "$add": [
  12. new Date(0),"d": {
  13. "$dayOfMonth": {
  14. "$add": [
  15. new Date(0),"$LASTLOGIN"] }
  16. ]
  17. }
  18. }
  19. }
  20. },group = {
  21. "$group": {
  22. "_id": {
  23. "year": "$y","month": "$m","day": "$d"
  24. },"count" : { "$sum" : 1 }
  25. }
  26. };

运行聚合管道:

  1. db.session_log.aggregate([ project,group ])

会给出以下结果(基于样本文件):

  1. { "_id" : { "year" : 2014,"month" : 1,"day" : 3 },"count" : 1 }

改进将是在单个管道中运行上述内容

  1. var group = {
  2. "$group": {
  3. "_id": {
  4. "year": {
  5. "$year": {
  6. "$add": [
  7. new Date(0),"$LASTLOGIN"] }
  8. ]
  9. }
  10. },"mmonth": {
  11. "$month": {
  12. "$add": [
  13. new Date(0),"day": {
  14. "$dayOfMonth": {
  15. "$add": [
  16. new Date(0),"$LASTLOGIN"] }
  17. ]
  18. }
  19. }
  20. },"count" : { "$sum" : 1 }
  21. }
  22. };

运行聚合管道:

  1. db.session_log.aggregate([ group ])

猜你在找的Bash相关文章