在项目中,需要从某个类集中【随机】抽取几条记录的需求。而 mongo 中是没有现成的实现方式的。
目前仅想到有 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);
}
}