Java 从Mongo DB游标获取信息
我正在使用MongoDB和Java 我试图找出Mongo DB中是否存在具有给定字符串的符号,如下所示 这是可行的,但问题是它向MOngo DB发出了两个调用,这非常昂贵。 我有没有办法把它简化为一个调用,使它更注重性能 这是我的密码Java 从Mongo DB游标获取信息,java,mongodb,Java,Mongodb,我正在使用MongoDB和Java 我试图找出Mongo DB中是否存在具有给定字符串的符号,如下所示 这是可行的,但问题是它向MOngo DB发出了两个调用,这非常昂贵。 我有没有办法把它简化为一个调用,使它更注重性能 这是我的密码 public class Test { public static void main(String args[]) { DBCursor cursor = null; DBCollection coll = nu
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
}
}
}
为什么要使用
count
?您可以使用DBCursor
的hasNext()
方法来测试是否提取了某些内容
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 = coll.find(query);
int count = cursor.count();
if (count >= 1) {
// Found
System.out.println(cursor.next());
} else {
// Not found
}
但是,如果要获取下一个元素(如果存在的话),应该使用第一种方法。为什么要使用count
?您可以使用DBCursor
的hasNext()
方法来测试是否提取了某些内容
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 = coll.find(query);
int count = cursor.count();
if (count >= 1) {
// Found
System.out.println(cursor.next());
} else {
// Not found
}
但是,如果要获取下一个元素(如果存在),则应该使用第一种方法。不需要显式调用来获取计数
cursor.hasNext()
将返回光标中是否有任何元素
cursor = coll.find(query);
while(cursor.hasNext()){
// found
}else{
// not found
}
您还可以使用cursor.count()
将count()
方法附加到find()查询以返回匹配文档的数量,如以下原型所示:
db.collection.find().count()
or
db.collection.count()
此操作实际上不执行find()
相反,该操作会对find()
返回的结果进行计数
您不需要显式调用来获取计数
cursor.hasNext()
将返回光标中是否有任何元素
cursor = coll.find(query);
while(cursor.hasNext()){
// found
}else{
// not found
}
您还可以使用cursor.count()
将count()
方法附加到find()查询以返回匹配文档的数量,如以下原型所示:
db.collection.find().count()
or
db.collection.count()
此操作实际上不执行find()
相反,该操作会对find()
返回的结果进行计数
谢谢Rohit,所以你的意思是说cursor.count();不会进行另一个数据库调用??我说的对吗???@PreethiJain。。是的,你是对的。它不会再打电话了。游标与JDBC中的ResultSet类似。您可以通过向前移动光标来访问每条记录,从而耗尽查询返回的整个结果;不会进行另一个数据库调用??我说的对吗???@PreethiJain。。是的,你是对的。它不会再打电话了。游标与JDBC中的ResultSet类似。您可以通过向前移动光标来访问每条记录,从而耗尽查询返回的整个结果。