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 }
} }
])
您需要将 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 ])