mongodb java中的mongodb问题有限制和排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13994065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongodb issue in java with limit and sort
提问by Franck
Collection:progs
集合:progs
{ "_id" : "ABC", "defaultDirectory" : "abc", "defaultRecvDirectory" : "abc" }
{ "_id" : "RAS", "defaultRecvDirectory" : "recv/ras" }
{ "_id" : "SND", "defaultSendDirectory" : "send/snd" }
In the mongo console:
在 mongo 控制台中:
db.progs.find({"_id":{"$lt":"ZZZZZZZZZ"}}).sort({"_id":-1}).limit(1);
==> { "_id" : "SND", "defaultSendDirectory" : "send/snd" }
In Java:
在 Java 中:
BasicDBObject query = new BasicDBObject();
query.put("_id", new BasicDBObject("$lt", "ZZZZZZZZZZ"));
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id","-1")).limit(1);
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
==> { "_id" : "ABC", "defaultSendDirectory" : "abc", "defaultRecvDirectory" : "abc" }
Someone can explain the difference?
有人可以解释一下区别吗?
回答by JohnnyHK
Remove the quotes from the "-1"
in your sort:
从"-1"
排序中删除引号:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id",-1)).limit(1);
Or use Mongodb ASC/DESC constants from com.mongodb.operation.OrderBy
instead of hardcoding 1 / -1
或者使用 Mongodb ASC/DESC 常量com.mongodb.operation.OrderBy
而不是硬编码 1 / -1
Example:
例子:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id", OrderBy.DESC.getIntRepresentation())).limit(1);
回答by Joel Mata
Another version based on MongoTemplate:
另一个基于 MongoTemplate 的版本:
public List<?> findLimitedSorted(Query query, Object target, String startFrom) {
query.limit(100);
query.with(new Sort(Sort.Direction.ASC, "<field_name>"));
return getMongoTemplate().find(query, target.getClass());
}
回答by Vinayak Mahadev
Getting DBObjects with sortting order from MongoDB:
从 MongoDB 获取具有排序顺序的 DBObjects:
List<DBObject> list = new LinkedList<DBObject>();
DBCursor cursor = db.getCollection("myCol").find().sort(new BasicDBObject("_id",-1)).limit(collection.find(query).count());
while(cursur.hasNext){
list.add(cursur.next());
}
if(!list.isEmpty())
for(DBObject dbo: list){
System.out.println(dbo);
}
else
System.out.println("List is empty");
回答by Aman Goel
Here is the solution which I found with filters, sorting and limit :
这是我找到的带有过滤器、排序和限制的解决方案:
List<Bson> queryFilters = new ArrayList<>();
queryFilters.add(Filters.eq(SavedReportEntity.FIELD_USER_ID, userId));
List<Document> documents = getMongoCollection().find(searchFilter).sort(sort).limit(10).into(new ArrayList<Document>());
you will get the list of Documents now you can play with it according to you.
您将获得文档列表,现在您可以根据自己的喜好使用它。