Dirk Dirk - 2 years ago 105
Javascript Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download