2012-12-27 67 views
0

我正在使用Mongo DB和Java。从Mongo DB光标获取信息

我想知道在Mongo DB中是否存在符号如下所示 这是行得通的,但问题在于它会对MOngo DB进行两次调用,这非常昂贵。 有没有什么办法可以将它减少到一个呼叫,并使其更注重性能。

这就是你为什么要使用count我所有的代码

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

?你可以使用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 
} 

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

+0

Thanks Rohit,所以你的意思是说cursor.count();不会进行另一个数据库调用?我对吗 ?? – Pawan

+0

@PreethiJain ..是的你是对的。它不会再打电话。游标就像JDBC中的ResultSet一样。您可以通过向前移动光标来访问每条记录,从而耗尽查询返回的整个结果。 –

+0

非常感谢Rohit。 – Pawan

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()方法的发现()查询返回匹配文档的数量,如下面的原型:

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

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

Reference