我有一系列文件如下。
{
"_id" : 1,
"_DeviceName" : "Main Panel",
"_Timestamp" : ISODate("2017-08-04T23:15:00.000+03:00"),
"_LocationID" : ObjectId("598459e86b41c036f051217c"),
"Meters" : {
"gasmeter" : 1000.0,
}},
{
"_id" : 2,
"_DeviceName" : "Main Panel",
"_Timestamp" : ISODate("2017-08-04T23:15:00.000+03:00"),
"_LocationID" : ObjectId("598459e86b41c036f051217c"),
"Meters" : {
"gasmeter" : 1007.0,
}},
{
"_id" : 3,
"_DeviceName" : "Main Panel",
"_Timestamp" : ISODate("2017-08-04T23:15:00.000+03:00"),
"_LocationID" : ObjectId("598459e86b41c036f051217c"),
"Meters" : {
"gasmeter" : 1010.0,
}}
我正试图解决燃气表元件之间的差异。
{差异:7} - Id = 1和Id = 2
之间的差异{差异:3} - Id = 2和Id = 3
之间的差异db.MeterData.aggregate([{$project: { item: 1, difference: {$subtract: [ {$add: [ "$Meters.gasmeter","$Meters.gasmeter" ] }, "$Meters.gasmeter" ] }}}])
但这不起作用。我仍然得到相同的价值。
知道如何使用mongodb进行聚合吗?
答案 0 :(得分:1)
因为我不完全确定你希望如何解决问题(在C#或mongo本身)。我在Mongo中想出了这个。
db.MeterData.find().forEach(
function (doc) {
var next = db.Sum.findOne({
_id: {
"$gt": NumberInt(doc._id)
}
})
if (next != null) {
var diff = next.Meters.gasmeter - doc.Meters.gasmeter;
printjson("{ difference : " + diff + "} - Difference between Id=" + doc._id + " and Id=" + next._id);
}
})
返回
"{ difference : 7} - Difference between Id=1 and Id=2"
"{ difference : 3} - Difference between Id=2 and Id=3"
我希望这对你有所帮助。