我在Google上搜索了很多,但没有找到任何有用的解决方案...我想找到每日用户的总数。
我有一个名为 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和
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count": { "$sum": 1 }
} }
])
您需要通过将值乘以1000将
LASTLOGIN
字段转换为毫秒时间戳{ "$multiply": [1000, "$LASTLOGIN"] }
,然后转换为日期
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
这可以在
$project
管道中完成,方法是将毫秒时间添加到零毫秒的Date(0)
对象,然后提取 $year
, $month
, 可以从您转换的日期开始使用 $dayOfMonth
管道,用于按日期对文档进行分组。因此,您应该将聚合管道更改为此:
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/