0

我正在使用带有 Java 的 Mongo DB。

我试图找出在 Mongo DB 中是否存在具有给定字符串的符号,如下所示。这是有效的,但问题是它对 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 
        } 
    }
}
4

2 回答 2

2

你为什么要使用count?您可以只使用 的hasNext()方法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引用:-

cursor  = coll.find(query);
int count = cursor.count();

if (count >= 1) {
    // Found
    System.out.println(cursor.next());
} else {
    // Not found
}

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

于 2012-12-27T06:02:22.613 回答
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().

参考

于 2012-12-27T06:48:55.540 回答