harry
harry

Reputation: 31

MongoDB query find the maximum value of the last two days

If I want to search maximum temperature from all record of the collection then below query is perfect

 db.posts3.aggregate([{$group:{ _id: "maximum",Temperature:{$max:"$Temperature"}}}]);

If I want to search the maximum temperature of the last two days the mongo query not work.

    db.posts3.aggregate([{$group:
         { _id: "maximum",
            {"time":{"$gt": ISODate("2019-10-12T11:25:06.156Z"),
                      "$lt":ISODate("2019-12-12T11:25:07.156Z")}
            },
                Temperature:{$max:"$Temperature"}

          }
       }
    ]);

Upvotes: 2

Views: 174

Answers (2)

prasad_
prasad_

Reputation: 14317

The following aggregation will get the maximum of the temp field for the dt within last 2 days.

db.test.aggregate( [
  { 
      $match: { 
          $expr: { 
              $gte:  [ "$dt", { $subtract: [ ISODate(), 2*24*60*60*1000 ] } ] 
          } 
      } 
  },
  { 
      $group: { 
          _id: null,
          maxTemp: { $max: "$temp" }
      }
  },
] )

The result is "maxTemp" : 14, with the following input documents:

{ "_id" : 1, "dt" : ISODate("2019-12-14T08:51:53.531Z"), "temp" : 12 }
{ "_id" : 2, "dt" : ISODate("2019-12-13T01:42:40.837Z"), "temp" : 13 }
{ "_id" : 3, "dt" : ISODate("2019-12-13T13:42:40.837Z"), "temp" : 14 }
{ "_id" : 4, "dt" : ISODate("2019-12-11T08:51:53.531Z"), "temp" : 15 }
{ "_id" : 9, "dt" : ISODate("2019-12-12T08:51:53.531Z"), "temp" : 16 }

Upvotes: 1

CNL
CNL

Reputation: 31

Moving the time search to $match pipeline may solve your problem:

db.posts3.aggregate([
  {$match:
    {"time": {
      "$gt": ISODate("2019-10-12T11:25:06.156Z"),
      "$lt":ISODate("2019-12-12T11:25:07.156Z")}
    }
  },
  {$group:
     { 
       _id: "maximum",
       Temperature:{$max:"$Temperature"}
     }
  }
]);

Upvotes: 3

Related Questions