mongo 从 collection 中随机查询多条记录
2016-03-16 11:14
501 查看
在项目中,需要从某个类集中【随机】抽取几条记录的需求。而 mongo 中是没有现成的实现方式的。
目前仅想到有 2 种方式:
在插入记录中,人为添加一个字段 random 字段。查询时使用 >e 和 <e 搭配使用查询出多条随机记录数
先使用 count 计算出总记录数,在使用随机的 skip 和 limit 搭配查询出多条随机记录数
好像可以使用地理索引,这方面没接触过,暂不考虑
显而易见的使用【方法一】是明智之选
目前仅想到有 2 种方式:
在插入记录中,人为添加一个字段 random 字段。查询时使用 >e 和 <e 搭配使用查询出多条随机记录数
先使用 count 计算出总记录数,在使用随机的 skip 和 limit 搭配查询出多条随机记录数
好像可以使用地理索引,这方面没接触过,暂不考虑
显而易见的使用【方法一】是明智之选
double rand = Math.random(); JSONObject query = new JSONObject(); query.put("random", new BasicDBObject("$gte", rand)); String fields = "{_id:0,letId:1,heroId:1,heroLevel:1}"; String sort = "{heroLevel:1}"; // 大于 随机值 条件查找记录 { MongoCursor<JSONObject> mongoCursor = getJgCollection().find(query.toString()).limit(10).sort(sort).projection(fields).as(JSONObject.class); while (mongoCursor.hasNext()) { JSONObject temp = mongoCursor.next(); array.add(temp); } } // 若未取得值,则用 小于 随机值 条件查找记录 if (array.size() == 0) { query.remove("$gte"); query.put("random", new BasicDBObject("$lte", rand)); MongoCursor<JSONObject> mongoCursor = getJgCollection().find(query.toString()).limit(10).sort(sort).projection(fields).as(JSONObject.class); while (mongoCursor.hasNext()) { JSONObject temp = mongoCursor.next(); array.add(temp); } }
相关文章推荐
- AlphaGo关键技术,Deep Learning(深度学习)<1>
- 一张图解AlphaGo原理及弱点
- Google浏览器Chrome安装失败解决办法
- algorithm@ find the shortest path in a graph using BFS
- 蓝桥杯 ALGO-122(记忆化搜索)
- SENGO森果网招商
- HOTPOWER.【专注游戏界面外包】/接游戏界面外包/logo外包/icon
- Django入门(九) ajax异步请求
- google zxing生成二维码
- 【每周一文】Googles News Personalization:Scalable Online Collaborative Filtering(2007)
- go源码阅读笔记(math.1)
- Django: 配置和静态文件
- 一张图解AlphaGo原理及弱点
- 一张图解AlphaGo原理及弱点
- 一张图解AlphaGo原理及弱点
- lightoj 1259 - Goldbach`s Conjecture 【素数筛】
- Chat Server's Outgoing Traffic(求助文)
- 搭建Go开发及调试环境(LiteIDE + GoClipse) -- Windows篇
- 蓝桥杯 ALGO-8(线段树)
- Agglomerative Hierarchical Algorithms(凝聚式层次聚类)