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?
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?
Share Improve this question asked Nov 2, 2015 at 14:58 DirkDirk 3,2215 gold badges34 silver badges38 bronze badges5 Answers
Reset to default 14It'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
}
})
You can use toArrray()
.
var arrayDoc = cursor.toArray();
arrayDoc[0]; //first element from cursor
or
arrayDoc = cursor.limit(1).toArray(); //limiting to one
const firstItem = cursor.next();
Just call next()
on the cursor. This will advance the cursor to the first element.
You can use:
cursor.fetch()[0];
fetch will return all object documents of the cursor. Regards,