Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


MongoDB Cursors


When the db.collection.find () function is used to search for documents in the collection, the result returns a pointer to the collection of documents returned which is called a cursor.
By default, the cursor will be iterated automatically when the result of the query is returned. But one can also explicitly go through the items returned in the cursor one by one. If you see the below example, if we have 3 documents in our collection, the cursor will point to the first document and then iterate through all of the documents of the collection.


{"employeeId":1, "employeeName": "employee1"},
{"employeeId":2, "employeeName": "employee2"},
{"employeeId":3, "employeeName": "employee3"}


The Cursor will start at the first record in the collection and then iterate through. The cursor.forEach() method is used to apply a JavaScript function for each document in a cursor. The cursor class also implements the iterator interface, so you can use it in a forEach loop:
The forEach() method has the following prototype form:


db.collection.find().forEach(<function>)


The following example invokes the forEach() method on the cursor returned by find() to print the name of each restaurant in the collection.


db.employees.find().forEach( function(myDoc) { print( "name: " + myDoc.employeeName); } );



Explanation:
First we take the result set of the query which finds the Employee's whose id is greater than 2 and assign it to the JavaScript variable 'myEmployee'
Next we use the while loop to iterate through all of the documents which are returned as part of the query.
Finally for each document, we print the details of that document in JSON readable format.
To iterate through the results, you can use the next method on the cursor. You can use hasNext to check whether there is another result. A typical loop through results looks like the following:


> while (cursor.hasNext()) {
... obj = cursor.next();
... // do stuff
... }


cursor.hasNext() checks that the next result exists, and cursor.next() fetches it.


     << Previous
Next >>