Mongodb 当日期为 unix 时间戳时按日期聚合文档
Mongodb aggregate documents by date when date is in unix time stamp
我是 mongodb 的新手,所以这一定是直截了当的查询。
我有如下集合,其中日期以 unix 毫秒为单位存储
[
{
"createdAt": 1596700221742,
"id": "5f2bb63da9babddd420d0fa6",
"quoteId": "SBA0005",
"commission": 0,
},
{
"createdAt": 1596699868976,
"id": "5f2bb4dcbcf1acdbb64137d0",
"quoteId": "SBA0004",
"commission": 0,
},
{
"createdAt": 1596698702729,
"id": "5f2bb04ebcf1acdbb64137ce",
"quoteId": "SBA0003",
"commission": 0,
},
{
"createdAt": 1596200445326,
"id": "5f2415fd9f248110a290aa29",
"quoteId": "SBA0002",
"commission": 100,
},
{
"createdAt": 1596200404548,
"id": "5f2415d49f248110a290aa28",
"quoteId": "SBA0001",
"commission": 100,
},
{
"createdAt": 1596200326783,
"id": "5f2415869f248110a290aa27",
"quoteId": "SBA0000",
"commission": 10,
}
]
我想在询问上周数据时按每天分组的结果。
[{
date: '06-08-2020',
count: 1,
totalcommision: 100},
{
date: '07-08-2020',
count: 2,
totalcommision: 1000
}]
有什么帮助吗?
您需要使用$toDate来转换以Unix毫秒为单位存储的日期。下面是聚合查询。
db.collection.aggregate([
{
"$addFields": {
"cdate": {
"$toDate": "$createdAt"
}
}
},
{
"$project": {
"ddate": {
"$concat": [
{
"$toString": {
$dayOfMonth: "$cdate"
}
},
"-",
{
"$toString": {
$month: "$cdate"
}
},
"-",
{
"$toString": {
$year: "$cdate"
}
}
]
},
"commission": 1
}
},
{
"$group": {
"_id": "$ddate",
"count": {
"$sum": 1
},
"totalCommision": {
"$sum": "$commission"
}
}
},
{
"$project": {
"date": "$_id",
"count": 1,
"totalCommision": 1,
"_id": 0
}
}
])
这是给你的MongoPlayground。
我是 mongodb 的新手,所以这一定是直截了当的查询。 我有如下集合,其中日期以 unix 毫秒为单位存储
[
{
"createdAt": 1596700221742,
"id": "5f2bb63da9babddd420d0fa6",
"quoteId": "SBA0005",
"commission": 0,
},
{
"createdAt": 1596699868976,
"id": "5f2bb4dcbcf1acdbb64137d0",
"quoteId": "SBA0004",
"commission": 0,
},
{
"createdAt": 1596698702729,
"id": "5f2bb04ebcf1acdbb64137ce",
"quoteId": "SBA0003",
"commission": 0,
},
{
"createdAt": 1596200445326,
"id": "5f2415fd9f248110a290aa29",
"quoteId": "SBA0002",
"commission": 100,
},
{
"createdAt": 1596200404548,
"id": "5f2415d49f248110a290aa28",
"quoteId": "SBA0001",
"commission": 100,
},
{
"createdAt": 1596200326783,
"id": "5f2415869f248110a290aa27",
"quoteId": "SBA0000",
"commission": 10,
}
]
我想在询问上周数据时按每天分组的结果。
[{
date: '06-08-2020',
count: 1,
totalcommision: 100},
{
date: '07-08-2020',
count: 2,
totalcommision: 1000
}]
有什么帮助吗?
您需要使用$toDate来转换以Unix毫秒为单位存储的日期。下面是聚合查询。
db.collection.aggregate([
{
"$addFields": {
"cdate": {
"$toDate": "$createdAt"
}
}
},
{
"$project": {
"ddate": {
"$concat": [
{
"$toString": {
$dayOfMonth: "$cdate"
}
},
"-",
{
"$toString": {
$month: "$cdate"
}
},
"-",
{
"$toString": {
$year: "$cdate"
}
}
]
},
"commission": 1
}
},
{
"$group": {
"_id": "$ddate",
"count": {
"$sum": 1
},
"totalCommision": {
"$sum": "$commission"
}
}
},
{
"$project": {
"date": "$_id",
"count": 1,
"totalCommision": 1,
"_id": 0
}
}
])
这是给你的MongoPlayground。