Mongo groupby month 使用 UNIX 毫秒时间 [英] Mongo groupby month using UNIX millisecond time
问题描述
我有一个 Mongo 集合,如下所示:
I have a Mongo collection that looks as follows:
[{
id: 1,
timestamp: 1534488870841,
type: 'deposit'
}, {
id: 1,
timestamp: 1534488915119,
type: 'deposit'
}]
如何查询以列出按月份分组的所有 deposit
交易.
How can I make a query to list all deposit
transactions, grouped by the month.
必须使用 timestamp
属性(UNIX 毫秒)计算月份.
The month must be calculated using the timestamp
attribute (UNIX millisecond).
我可以按如下方式获得押金,但我不确定如何分组:
I can get the deposit's as follows but I am unsure on how to group:
db.getCollection('transactions').find(
{"type":"deposit"});
编辑:Mongo 3.4 版
Edit: Mongo version 3.4
推荐答案
你可以在mongodb中尝试下面的聚合4.0
You can try below aggregation in mongodb 4.0
您可以使用 <将 timestamp
转换为日期strong>$toDate
聚合,然后是 $group
与 $month
聚合
You can convert timestamp
to date using $toDate
aggregation and then $group
with $month
aggregation
db.collection.aggregate([
{ "$match": { "type": "deposits" }},
{ "$addFields": {
"date": {
"$toDate": "$timestamp"
}
}},
{ "$group": {
"_id": { "$month": "$date" },
"deposits": {
"$push": "$$ROOT"
}
}}
])
您可以在 mongodb 3.4
You can try below aggregation in mongodb 3.4
在 3.4 中,您可以将 timestamp
转换为日期,方法是在其中添加 new Date()
和 $group
使用 $dateToString
聚合
In 3.4 you can convert timestamp
to date by adding new Date()
in it and $group
it by using $dateToString
aggregation
db.collection.aggregate([
{ "$match": { "type": "deposits" }},
{ "$addFields": {
"date": {
"$add": [ new Date(0), "$timestamp" ]
}
}},
{ "$group": {
"_id": {
"$dateToString": {
"format": "%m",
"date": "$date"
}
},
"deposits": {
"$push": "$$ROOT"
}
}}
])
这篇关于Mongo groupby month 使用 UNIX 毫秒时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!