Mongo按月份使用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
您可以使用 $month
聚合
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 中,您可以在其中添加new Date()
并"> $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按月份使用UNIX毫秒分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!