读书人

MongoDB里面如何 查最值

发布时间: 2012-12-21 12:03:49 作者: rapoo

MongoDB里面怎么 查最值

怎么在MongoDB里面怎么 查最值 ?就好像SQL语句的select MAX(row) form ....


我现在知道了,现在拿出来和大家分享一下吧 ?MongoDB里面如何 查最值



DBObject ref = new BasicDBObject();

ref.put("auth_id", authId);

ref.put("weibo_type", weiboType);


DBObject keys = new BasicDBObject("weibo_id", 1);


DBObject orderBy = new BasicDBObject("weibo_id", -1);// -1标示降序 1表示升序


DBCursor dbc = statusColl.find(ref, keys).sort(orderBy).limit(1);


DBObject dbo = null;

try {

dbo = dbc.next();

} catch (NoSuchElementException e) {

return -1L;

}

return (Long) dbo.get("weibo_id");


大概就是上面那个样子啦,根据您自己的业务需求,写出符合条件的代码吧,主要就是find()和limit()这两根函数而已,下面的这个大家可以无视,我是写给自己看的



List<Status> list = new LinkedList<Status>();

DBObject ref = new BasicDBObject();


ref.put("user_id", userId);


DBObject orderBy = new BasicDBObject("create_at", -1); // -1标示降序 1表示升序


DBCursor res = homePagesColl.find(ref).sort(orderBy).skip(

(pageNumber - 1) * nPerPage).limit(nPerPage);


while (res.hasNext()) {

Object obj = res.next().get("weibo_content");

Status sta = new Status(new JSONObject(obj.toString()));

list.add(sta);

}

return list;

?

if (tableName == null)
tableName = IConstants.MONITOR;

BasicDBObject query = conditionToBasicDBObject(condition);

DBCursor cursor = db.getCollection(tableName).find(query).sort(
new BasicDBObject(perprotyName, -1)).limit(1);
while (cursor.hasNext()) {
DBObject dbo = cursor.next();
obj = dbo;
break;
}
cursor.close();

return obj;</pre>
<p>?</p>
<p>?</p>
<p>?</p> 2 楼 happy90 2011-04-12 2楼的思路是先降序排序,然后取第一个,是吗?
难道MongoDB里面没有直接取MAX的功能吗?... 3 楼 kimmking 2011-04-12 happy90 写道2楼的思路是先降序排序,然后取第一个,是吗?
难道MongoDB里面没有直接取MAX的功能吗?...
对,没有sql里的 max。~

sort-limit本身,这个不就是max吗?

-----------------
ps: mongodb的find里有max/min 语法,
不过其相当于<= 和 >=

referred: http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

读书人网 >其他数据库

热点推荐