我用谷歌搜索了很多,但没有找到任何有用的解决方案...我想查找每日用户总数。 我有一个名为 session_log 的集合,其中包含以下文档
{
"_id" : ObjectId("52c690955d3cdd831504ce30"),
"SORTID" : NumberLong(1388744853),
"PLAYERID" : 3,
"LASTLOGIN" : NumberLong(1388744461),
"ISLOGIN" : 1,
"LOGOUT" : NumberLong(1388744853)
}
我想从 LASTLOGIN 聚合...
这是我的查询:
db.session_log.aggregate(
{ $group : {
_id: {
LASTLOGIN : "$LASTLOGIN"
},
count: { $sum: 1 }
}}
);
但它是按每次登录时间而不是每天汇总的。任何帮助将不胜感激
最佳答案
MongoDB 4.0 及更新版本
使用 $toDate
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$toDate": {
"$multiply": [1000, "$LASTLOGIN"]
}
}
}
},
"count": { "$sum": 1 }
} }
])
或 $convert
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$convert": {
"input": {
"$multiply": [1000, "$LASTLOGIN"]
},
"to": "date"
}
}
}
},
"count": { "$sum": 1 }
} }
])
MongoDB >= 3.0 和 <4.0:
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count": { "$sum": 1 }
} }
])
您需要将 LASTLOGIN
字段通过将值乘以 1000 来转换为毫秒时间戳
{ "$multiply": [1000, "$LASTLOGIN"] }
,然后转换为日期
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
这可以在 $project
中完成 管道,通过将毫秒时间添加到零毫秒 Date(0)
对象,然后提取 $year
, $month
, $dayOfMonth
部分来自转换后的日期,然后您可以在 $group
中使用这些部分 按天对文档进行分组的管道。
因此,您应该将聚合管道更改为:
var project = {
"$project":{
"_id": 0,
"y": {
"$year": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"m": {
"$month": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"d": {
"$dayOfMonth": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
}
},
group = {
"$group": {
"_id": {
"year": "$y",
"month": "$m",
"day": "$d"
},
"count" : { "$sum" : 1 }
}
};
运行聚合管道:
db.session_log.aggregate([ project, group ])
将给出以下结果(基于示例文档):
{ "_id" : { "year" : 2014, "month" : 1, "day" : 3 }, "count" : 1 }
一个改进是在单个管道中运行上述内容
var group = {
"$group": {
"_id": {
"year": {
"$year": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"mmonth": {
"$month": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"day": {
"$dayOfMonth": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count" : { "$sum" : 1 }
}
};
运行聚合管道:
db.session_log.aggregate([ group ])
关于基于unix时间戳的mongodb按天聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33078773/