如何使用mongodb 3.2使用范围查询

时间:2016-02-24 07:59:32

标签: java mongodb

我正在使用mongodb 3.2版本。我正在尝试对以下数据集使用以下查询。但由于以下异常,我无法获取记录:

Exception in thread "main" java.util.NoSuchElementException
    at com.mongodb.QueryResultIterator.next(QueryResultIterator.java:103)

我的数据集:

BasicDBObject obj3 = new BasicDBObject();
obj3.put("name", "Dhoni");
obj3.put("location", "Ranchi");
obj3.put("Profession", "Cricketer");
obj3.put("number", 3);

BasicDBObject obj4 = new BasicDBObject();
obj4.put("name", "Sakshi");
obj4.put("location", "Ranchi");
obj4.put("Profession", "HtlMgmt");
obj4.put("number", 4);

BasicDBObject obj5 = new BasicDBObject();
obj5.put("name", "Ziva");
obj5.put("location", "Ranchi");
obj5.put("Profession", "Player");
obj5.put("number", 5);

我的查询:

BasicDBObject gtquery = new BasicDBObject();
        gtquery.put("number",new BasicDBObject("$gt",3).append("$lt",5));

        DBCursor cursor4 = col.find(gtquery);
        while(cursor4.hasNext()){
            System.out.println(cursor.next());
        }

任何人都可以帮我解决这个例外......

1 个答案:

答案 0 :(得分:1)

要获得范围,比如3<数字< 5,将您的查询更改为:

BasicDBObject gtquery = new BasicDBObject("number", 
    new BasicDBObject("$gt", 3).append("$lt", 5)
);

DBCursor cur = col.find(gtquery);
try {
    while (cur.hasNext()) {
        System.out.println(cur.next());
    }
} finally {
    cur.close();
}