Find Max Value in MongoDB by Using Spring Data MongoDb

Viewed 364

Actually i need to find select MAX(lastUpdatedTime) from TABLE

i am doing:

TableRepositoryImpl.java

*maxTime(){
Query query= new Query().limit(1).with(Sort.by(Sort.Direction.DESC, "lastUpdatedTime"))
return mongoTemplate.findOne(query, TABLE.class)
}*

but this sort method take extra time, can anybody knows how to implement by using MAX function as we do in sql. or any other optimize way, i just need to find the lates updated timeStamp in my mongoDB

2 Answers

You can use the $max aggregation:

[
  {
    "_id": 1,
    "item": "abc",
    "price": 10,
    "quantity": 2,
    "date": ISODate("2014-01-01T08:00:00Z")
  },
  {
    "_id": 2,
    "item": "jkl",
    "price": 20,
    "quantity": 1,
    "date": ISODate("2014-02-03T09:00:00Z")
  },
  {
    "_id": 3,
    "item": "xyz",
    "price": 5,
    "quantity": 5,
    "date": ISODate("2014-02-03T09:05:00Z")
  },
  {
    "_id": 4,
    "item": "abc",
    "price": 10,
    "quantity": 10,
    "date": ISODate("2014-02-15T08:00:00Z")
  },
  {
    "_id": 5,
    "item": "xyz",
    "price": 5,
    "quantity": 10,
    "date": ISODate("2014-02-15T09:05:00Z")
  }
]
db.collection.aggregate({
  $group: {
    _id: null,
    max: {
      $max: "$date"
    }
  }
})

which returns the max of date:

[
  {
    "_id": null,
    "max": ISODate("2014-02-15T09:05:00Z")
  }
]

try

GroupOperation groupMaxOperation = Aggregation.group().max("lastUpdatedTime").as("maxLastUpdatedTime");

AggregationResults<Document> aggregate = mongoTemplate.aggregate(Aggregation.newAggregation(groupMaxOperation), TABLE.class, Document.class);

Optional<Date> maxLastUpdatedTime = Optional.ofNullable(aggregate.getUniqueMappedResult())
                .map(result -> result.get("maxLastUpdatedTime", Date.class));

If the mongo collection(TABLE) is large, you might need to add allowDiskUse to the aggregation

AggregationResults<Document> aggregate = mongoOps.aggregate(Aggregation.newAggregation(groupMaxOperation)
                        .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build()),
                TABLE.class, Document.class);
Related