我是MongoDb的新手,希望您对此查询有所帮助。我用基于日期字段获取最近5天的数据编写了以下汇总管道,但是一个小问题是所有数据都在问如何只获取5天的数据和任何用户的消耗总和。
df = pd.DataFrame(
data=[
['01-01-2018', 'Jakob', 5, 10],
['01-01-2018', 'Adomas', 10, 20],
['01-01-2018', 'Thomas', 15, 30],
['01-02-2018', 'Jakob', 50, 30],
['01-02-2018', 'Adomas', 100, 40],
['01-02-2018', 'Thomas', 150, 65],
['01-03-2018', 'Jakob', 60, 30],
['01-03-2018', 'Adomas', 120, 45],
['01-03-2018', 'Thomas', 200, 75]
],
columns=['Date', 'Sales rep', 'item A', 'item B']
)
cum_columns = ['item A', 'item B']
result = df.merge(
df.groupby('Sales rep')[cum_columns].diff(),
left_index=True, right_index=True, suffixes=['', '_uncum']
).fillna({'{}_uncum'.format(cum_column): df[cum_column] for cum_column in cum_columns})
print(result)
Out:
Date Sales rep item A item B item A_uncum item B_uncum
0 01-01-2018 Jakob 5 10 5.0 10.0
1 01-01-2018 Adomas 10 20 10.0 20.0
2 01-01-2018 Thomas 15 30 15.0 30.0
3 01-02-2018 Jakob 50 30 45.0 20.0
4 01-02-2018 Adomas 100 40 90.0 20.0
5 01-02-2018 Thomas 150 65 135.0 35.0
6 01-03-2018 Jakob 60 30 10.0 0.0
7 01-03-2018 Adomas 120 45 20.0 5.0
8 01-03-2018 Thomas 200 75 50.0 10.0
这是我的数据集。
我用它来获取最近5天的数据。
{
"timeId" : ISODate("2018-09-10T16:40:08.817Z"),
"vendor" : "CIMCON",
"slcId" : "123450"
"mongoStreetLightChildVo" : {
"deviceType" : "L",
"totalStreetLights" : 3.0,
"totalConsumptionMtd" : "2"
"mongoStreetLightChildVo1s" : [
{
"date" : ISODate("2018-09-01T16:40:08.817Z"),
"consumption" : 27.0,
"burnHours" : 24.0
},
{
"date" : ISODate("2018-09-02T16:40:08.817Z"),
"consumption" : 2.0,
"burnHours" : 24.0
},
{
"date" : ISODate("2018-09-03T16:40:08.817Z"),
"consumption" : 287.0,
"burnHours" : 20.0
},
{
"date" : ISODate("2018-09-04T16:40:08.817Z"),
"consumption" : 209.0,
"burnHours" : 2.0
},
{
"date" : ISODate("2018-09-05T16:40:08.817Z"),
"consumption" : 243.0,
"burnHours" : 4.0
},
{
"date" : ISODate("2018-09-06T16:40:08.817Z"),
"consumption" : 254.0,
"burnHours" : 4.0
},
{
"date" : ISODate("2018-09-07T16:40:08.817Z"),
"consumption" : 235.0,
"burnHours" : 24.0
},
{
"date" : ISODate("2018-09-08T16:40:08.817Z"),
"consumption" : 62.0,
"burnHours" : 24.0
},
{
"date" : ISODate("2018-09-09T16:40:08.817Z"),
"consumption" : 2.0,
"burnHours" : 23.0
},
{
"date" : ISODate("2018-09-10T02:40:08.817Z"),
"consumption" : 26.0,
"burnHours" : 27.0
}
]
}
}
如何仅获取5天数据
我所需的输出是:
db.collection.aggregate([
{$match:{
"mongoStreetLightChildVo.mongoStreetLightChildVo1s.date":
{
$gte: new Date((new Date().getTime() - (5 * 24 * 60 * 60 * 1000)))
}
}
},
{$project:{
"mongoStreetLightChildVo.mongoStreetLightChildVo1s.date":1,
"mongoStreetLightChildVo.mongoStreetLightChildVo1s.consumption":1
}}
])