最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the first element of a Mongo cursor - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a comment  | 

5 Answers 5

Reset to default 14

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
    }
})

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,

发布评论

评论列表(0)

  1. 暂无评论