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?
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.
You can use the cursor method forEach() to iterate the cursor and access the documents, as in the following example: var myCursor = db.
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.
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.
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.
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
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With