简体   繁体   English

对mongoDb游标进行排序

[英]Sorting a mongoDb Cursor

I'm having difficulties finding the right syntax for my sorted cursor. 我很难为排序的游标找到正确的语法。

What it needs to do is return a sorted cursor which I can then iterate after each item is processed. 它需要做的是返回一个排序的游标,在处理完每个项目之后,我可以对其进行迭代。

Here's my function which works perfectly without the sort, but returns nothing once sort() added (I strongly suspect a syntax issue but can't seem to find the right doc): 这是我的函数,无需排序即可完美工作,但一旦添加sort() ,则什么也不返回(我强烈怀疑语法问题,但似乎找不到正确的文档):

db.collection('products').find({}).sort({rnd: 1},function(err, cursor){
    console.log(found);
    if(err){
        console.log(err);
    }
    function processItem(err, item) {
        if(err){
            console.log(err);
        }
        if(item === null) {
            console.log('cursor exhausted');
            db.close();
        }else{
            someAsyncOperation(item,function(){
                cursor.nextObject(processItem);
            });
        }
    }
    cursor.nextObject(processItem);
});

I was making a wrong assumption about the syntax. 我对语法有错误的假设。 The cursor returned by find() needs to be sorted, then iterated like so : 需要对find()返回的游标进行排序,然后像这样进行迭代:

var cursor = db.collection('products4Scrape').find({}).sort({rnd: 1});
iterateCursor();

function iterateCursor(){
    if(err){
        console.log(err);
    }
    function processItem(err, item) {
        if(err){
            console.log(err);
        }
        if(item === null) {
            console.log('cursor exhausted');
            db.close();
        }else{
            someAsyncOperation(item,function(){
                cursor.nextObject(processItem);
            });
        }
    }
    cursor.nextObject(processItem);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM