从Mongo DB Cursor获取信息

时间:2012-12-27 05:41:55

标签: java mongodb

我正在使用Mongo DB With Java。

我试图找出Mongo DB中是否存在具有给定String的Symbol,如下所示 这是有效的,但问题是它正在对MOngo DB进行两次调用,这非常昂贵。 有什么方法可以将它减少到一个电话并使其更加注重性能。

这是我的代码

public class Test
{
    public static void main(String args[])
    {
        DBCursor cursor  = null;
        DBCollection coll = null;
        BasicDBObject query = new BasicDBObject();
        String symbol = args[0];
        query.put("symbol", "" + symbol);
        cursor  = coll.find(query);
        int count = coll.find(query).count();

        /* Here is want to avoid the count call , is there anyway by which
           the cursor the obtained cursor tells , that there exists the symbol
           in Mongo DB */

        if(count>=1)
        {
            // If found then do 
            if (cursor != null) {

            }
        }
        else
        {
            // If Not  found then do 
        } 
    }
}

2 个答案:

答案 0 :(得分:2)

你为什么要使用count?您可以使用hasNext()的{​​{1}}方法来测试是否提取了某些内容。

DBCursor

但是,如果您想使用cursor = coll.find(query); if (cursor.hasNext()) { // Found System.out.println(cursor.next()); } else { // Not found } 方法,那么您也不必触发新查询。由于count()仅返回db.collection.find()。因此,您使用的DBCursor方法位于返回的count上。因此,只需在同一个DBCursor引用上调用count(): -

cursor

但是,如果你想获取下一个元素(如果存在的话),你应该使用第一种方法。

答案 1 :(得分:2)

您无需进行显式调用即可获得计数。

cursor.hasNext()将返回游标中是否有任何元素。

    cursor  = coll.find(query);
    while(cursor.hasNext()){
     // found
    }else{
     // not found
    }

您也可以使用cursor.count()

The count() method counts the number of documents referenced by a cursor. 

count()方法附加到find()查询以返回匹配文档的数量,如以下原型所示:

db.collection.find().count()
   or 
db.collection.count()

此操作实际上并不执行find();,操作会计算find()返回的结果。

Reference

相关问题