Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first element of a Mongo cursor

I can iterate through all the elements of a cursor (up to the number returned) using:

cursor.each(function(err, doc)

But how to I just get the first element from the cursor?

like image 1000
Dirk Avatar asked Nov 02 '15 14:11

Dirk


People also ask

How do I get MongoDB cursor?

In MongoDB, the find() method return the cursor, now to access the document we need to iterate the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate cursor manually.

How do I iterate through a cursor object?

You can use the cursor method forEach() to iterate the cursor and access the documents, as in the following example: var myCursor = db.

What is open cursor in MongoDB?

The Cursor is a MongoDB Collection of the document which is returned upon the find method execution. By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. It is just like a pointer which is pointing upon a specific index value.

How do I know if my MongoDB cursor is empty?

Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.


2 Answers

It's terribly inefficiently to call toArray if you just want the first doc of the results. Instead, call next on the cursor:

cursor.next(function(err, doc) {
    if (doc) {
        ...
    }
});

Another option is to just call findOne instead of find if you only want a single doc anyway.

like image 95
JohnnyHK Avatar answered Oct 06 '22 02:10

JohnnyHK


You can convert cursor you get into array. Try this

cursor.toArray(function(err,result){
    if(result)
    {
       //result[0] will give you first element from cursor
    }
})
like image 27
Vishnu gondlekar Avatar answered Oct 06 '22 03:10

Vishnu gondlekar