Pawan
Pawan

Reputation: 32321

Obtaining information from Mongo DB Cursor

I am using Mongo DB With Java .

I am trying to find out if there exists a Symbol with the given String in the Mongo DB as shown below This is working , but the problem is that it is making two calls to the MOngo DB , which is very expensive . Is there any way i can reduce it to one call and make it more performance oriented .

This is my code

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 
        } 
    }
}

Upvotes: 0

Views: 2833

Answers (2)

Rahul
Rahul

Reputation: 16335

You do not need to make an explicit call to get the count.

cursor.hasNext() will return whether there is any element in the cursor or not.

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

You can also use cursor.count()

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

Append the count() method to a find() query to return the number of matching documents, as in the following prototype:

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

This operation does not actually perform the find(); instead, the operation counts the results that would be returned by the find().

Reference

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213193

Why are you using count at all? You can just use the hasNext() method of DBCursor to test whether something is fetched or not.

cursor  = coll.find(query);

if (cursor.hasNext()) {
    // Found
    System.out.println(cursor.next());
} else {
    // Not found
}

However, if you want to use count() method, then also you don't have to fire a new query. Since db.collection.find() returns a DBCursor only. So, the count method you are using is on the returned DBCursor. So, just invoke count() on the same cursor reference: -

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

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

But, you should use the first approach, if you want to fetch the next element if present.

Upvotes: 2

Related Questions