我是Mongo聚合的新手。我想计算两个值之间的差异(每天的最后一个集合 - 每天的第一个集合)。许多资源名称每5分钟的数据库记录数据。结构该文件是:
{
_id : ObjectId("5820511a95d447ed648b45d6"),
DeviceName : "OLT01FTV",
ResourceName : "CM MAC:00-07-11-11-39-20",
CollectionTime : ISODate("2016-11-07T09:30:00.000+01:00"),
GranularityPeriod : 5,
A : 0,
B: 17,
C: 4,
D: 21,
E: 3,
F: 0
}
A,B ...... F是不同的柜台。 下面是我想要的例子:
([
{ "$match": {
"CollectionTime": {
$gte: ISODate("2016-09-05T00:00:00.000Z"),
$lt: ISODate("2016-10-07T00:00:00.000Z")
}
}},
{ "$unwind": "$u2000" },
{ "$group": {
"_id": null,
"firstUC": { "$first": "$UC" },
"lastUC": { "$last": "$UC" },
"firstSM-MISS": { "$first": "$SM-MISS" },
"lastSM-MISS": { "$last": "$SM-MISS" }
}},
{ "$project": {
"diff": {
"$divide": [
{ "$subtract": [ "$firstUC", "$lastUC" ] },
{ "$subtract": [ "$firstSM-MISS", "$lastSM-MISS" ] }
]
}
}}
])
答案 0 :(得分:0)
这将为您提供上述方案的“A”值之间的差异。如果你想为它们获得差异,你可以添加其他字段。
db.collection.aggregate([
{ "$match": {
"CollectionTime": {
$gte: ISODate("2016-11-01T00:00:00.000Z"),
$lt: ISODate("2016-11-30T00:00:00.000Z")
}
}},
{ "$sort": { "CollectionTime": 1 } },
{ "$group": {
"_id": null,
"firstA": { "$first": "$A" },
"lastA": { "$last": "$A" }
}},
{ "$project": {
_id: 0,
diffA: {
$subtract: [ "$lastA", "$firstA"]
}
}}
])
*编辑*
因此,我使用以下示例文档来创建以下示例文档以匹配您的架构:
// Create 3 Documents 1 second apart
for (var i = 1; i < 4; i++) {
db.foo.insert({
DeviceName : "OLT01FTV",
ResourceName : "CM MAC:00-07-11-11-39-20",
CollectionTime : new Date(),
GranularityPeriod : 5,
A : 1*i,
B: 2*i,
C: 3*i,
D: 4*i,
E: 5*i,
F: 6*i
})
sleep(1000); // To add a delay between insertions so we can visibly see the date difference
}
这导致创建以下3个文档:
> db.foo.find().pretty()
{
"_id" : ObjectId("582b1a6ced19a7334a5dee31"),
"DeviceName" : "OLT01FTV",
"ResourceName" : "CM MAC:00-07-11-11-39-20",
"CollectionTime" : ISODate("2016-11-15T14:23:40.934Z"),
"GranularityPeriod" : 5,
"A" : 1,
"B" : 2,
"C" : 3,
"D" : 4,
"E" : 5,
"F" : 6
}
{
"_id" : ObjectId("582b1a6ded19a7334a5dee32"),
"DeviceName" : "OLT01FTV",
"ResourceName" : "CM MAC:00-07-11-11-39-20",
"CollectionTime" : ISODate("2016-11-15T14:23:41.936Z"),
"GranularityPeriod" : 5,
"A" : 2,
"B" : 4,
"C" : 6,
"D" : 8,
"E" : 10,
"F" : 12
}
{
"_id" : ObjectId("582b1a6eed19a7334a5dee33"),
"DeviceName" : "OLT01FTV",
"ResourceName" : "CM MAC:00-07-11-11-39-20",
"CollectionTime" : ISODate("2016-11-15T14:23:42.939Z"),
"GranularityPeriod" : 5,
"A" : 3,
"B" : 6,
"C" : 9,
"D" : 12,
"E" : 15,
"F" : 18
}
聚合管道的第一步将匹配日期范围之间的所有文档 - 我设置为11月初...所以不用担心,然后排序将按收集时间排序:
分组后,我们有一个带有firstA和lastA值的文档:
{ "_id" : null, "firstA" : 1, "lastA" : 3 }
最后 - 在投影中执行减法并隐藏ID字段:
{ "diffA" : 2 }