Spring Data MongoDB : get last modified records (date sorting)

摘要: In Mongodb, you can use sort()to do the date sorting.

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

  1. MongoDB sort()
  2. Spring Data MongoDB : Query Document

上一篇: Java Time elapsed in days, hours, minutes, seconds
下一篇: Spring Data MongoDB : like query example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号