Spring Data MongoDB : get last modified records (date sorting)
By:Roy.LiuLast updated:2019-08-17
In Mongodb, you can use sort()to do the date sorting.
1. MongoDB Sorting Examples
In Mongodb, to sort a “date” field, issues :
//The '1' = sort ascending (oldest to newest) db.domain.find().sort({lastModifiedDate:1}) { "_id" : 1, "lastModifiedDate" : ISODate("2013-08-13T07:18:04.774Z") } { "_id" : 2, "lastModifiedDate" : ISODate("2013-09-03T08:12:16.309Z") } { "_id" : 3, "lastModifiedDate" : ISODate("2013-10-03T08:12:16.309Z") } { "_id" : 4, "lastModifiedDate" : ISODate("2013-11-03T08:12:16.326Z") } { "_id" : 5, "lastModifiedDate" : ISODate("2013-12-03T08:12:16.345Z") }
or
//The '-1' = sort descending (newest to oldest) db.domain.find().sort({lastModifiedDate:-1}) { "_id" : 5, "lastModifiedDate" : ISODate("2013-12-03T08:12:16.345Z") } { "_id" : 4, "lastModifiedDate" : ISODate("2013-11-03T08:12:16.326Z") } { "_id" : 3, "lastModifiedDate" : ISODate("2013-10-03T08:12:16.309Z") } { "_id" : 2, "lastModifiedDate" : ISODate("2013-09-03T08:12:16.309Z") } { "_id" : 1, "lastModifiedDate" : ISODate("2013-08-13T07:18:04.774Z") }
If the field “lastModifiedDate” is not indexed, and returns too much data, sorting will fail and raise below error message
db.domain.find().sort({lastModifiedDate:-1}) Sat Oct 12 11:51:43.055 JavaScript execution failed: SyntaxError: Unexpected token : > db.domain.find({},{domainName:1}).sort({lastModifiedDate:1}); error: { "$err" : "too much data for sort() with no index. add an index or specify a smaller limit" "code" : 10128
To fix it, always add limit() together with sort().
db.domain.find().sort({lastModifiedDate:-1}).limit(10)
2. Spring Data MongoDB : Sorting Examples
In Spring data, use this :
import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; //... Query query = new Query(); query.limit(10); query.with(new Sort(Sort.Direction.DESC, "lastModifiedDate")); mongoOperation.find(query, Domain.class);
References
From:一号门
COMMENTS