Mongodb可以从下一个中减去文档值。

时间:2021-01-19 02:54:30

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

{差异:7}- Id=1和Id=2之间的差异

{ difference : 3 } - Difference between Id=2 and Id=3

{差异:3}- Id=2和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?

你知道怎么用mongodb进行聚合吗?

1 个解决方案

#1


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.

因为我不完全确定您希望如何解决这个问题(使用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);
    }
})

Which returns

它返回

"{ difference : 7} - Difference between Id=1 and Id=2"

{差异:7}- Id=1和Id=2之间的差异

"{ difference : 3} - Difference between Id=2 and Id=3"

{差异:3}- Id=2和Id=3之间的差异

I hope this helps you a bit.

我希望这对你有帮助。

#1


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.

因为我不完全确定您希望如何解决这个问题(使用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);
    }
})

Which returns

它返回

"{ difference : 7} - Difference between Id=1 and Id=2"

{差异:7}- Id=1和Id=2之间的差异

"{ difference : 3} - Difference between Id=2 and Id=3"

{差异:3}- Id=2和Id=3之间的差异

I hope this helps you a bit.

我希望这对你有帮助。