我的文档以这种方式存储,不,我无法更改它们:
{
"_id" : ObjectId("5ea773f219d60c4f1629203a"),
"direction" : 135,
"latitude" : -3.744851,
"longitude" : -38.545571,
"metrictimestamp" : "20180201025959",
"odometer" : 55697826,
"routecode" : 0,
"speed" : 3,
"deviceid" : 134680,
"vehicleid" : 32040
}
我需要从这个“ metrictimestamp”中按车辆识别号分组,并且只需要一年中的某一天,并计算具有相同车辆和日期,想法的多少文件?
答案 0 :(得分:1)
我想说您的metrictimestamp
可能包含前几个字符20180201
作为YYYYMMDD
,因此使用$substrbytes进行聚合可以从字符串中获取月,日,年。尝试以下查询:
db.collection.aggregate([
{
$addFields: {
day: { $toInt: { $substrBytes: [ "$metrictimestamp", 6, 2 ] } }, // $toInt can be optional
month: { $toInt: { $substrBytes: [ "$metrictimestamp", 4, 2 ] } },
year: { $toInt: { $substrBytes: [ "$metrictimestamp", 0, 4 ] } }
}
},
{
$group: {
_id: { vehicleid: "$vehicleid", day: "$day", year: "$year" },
count: { $sum: 1 }
}
}
])
测试: mongoplayground