问题
I have a collection of documents as below.
Example of my collection documents
{
"_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,
}}
And I am trying to get the difference between the gasmeter elements.
Expected Result
{ difference : 7 } - Difference between Id=1 and Id=2
{ difference : 3 } - Difference between Id=2 and Id=3
What I tried
db.MeterData.aggregate([{$project: { item: 1, difference: {$subtract: [ {$add: [ "$Meters.gasmeter","$Meters.gasmeter" ] }, "$Meters.gasmeter" ] }}}])
But this does not work. I still get the same values.
Any idea how to do that aggregation with mongodb?
回答1:
Since I'm not entirely sure how you wish to solve the problem (in C# or mongo itself). I've come up with this in 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);
}
})
Which returns
"{ difference : 7} - Difference between Id=1 and Id=2"
"{ difference : 3} - Difference between Id=2 and Id=3"
I hope this helps you a bit.
来源:https://stackoverflow.com/questions/46061846/mongodb-subtract-document-value-from-the-next-one