收集:progs的
{ "_id" : "ABC", "defaultDirectory" : "abc", "defaultRecvDirectory" : "abc" }
{ "_id" : "RAS", "defaultRecvDirectory" : "recv/ras" }
{ "_id" : "SND", "defaultSendDirectory" : "send/snd" }
在mongo控制台中:
db.progs.find({"_id":{"$lt":"ZZZZZZZZZ"}}).sort({"_id":-1}).limit(1);
==> { "_id" : "SND", "defaultSendDirectory" : "send/snd" }
在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" }
有人可以解释这种差异吗?
答案 0 :(得分:28)
从您排序的"-1"
中删除引号:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id",-1)).limit(1);
或者使用来自com.mongodb.operation.OrderBy
的Mongodb ASC / DESC常量而不是硬编码1 / -1
示例:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id", OrderBy.DESC.getIntRepresentation())).limit(1);
答案 1 :(得分:2)
另一个基于MongoTemplate的版本:
width: calc(25% - 30px)
答案 2 :(得分:0)
以下是我在过滤器,排序和限制中找到的解决方案:
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>());
您将获得现在可以根据您使用的文档列表。
答案 3 :(得分:0)
从MongoDB获取具有排序顺序的DBObject:
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");