如何使用Node.js在MongoDB中使用cursor.forEach()? [英] How can I use a cursor.forEach() in MongoDB using Node.js?

查看:175
本文介绍了如何使用Node.js在MongoDB中使用cursor.forEach()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有大量文档,我想知道如何遍历所有文档并更新它们,每个文档具有不同的值.

I have a huge collection of documents in my DB and I'm wondering how can I run through all the documents and update them, each document with a different value.

推荐答案

答案取决于您使用的驱动程序.我知道的所有MongoDB驱动程序都以一种或另一种方式实现了cursor.forEach().

The answer depends on the driver you're using. All MongoDB drivers I know have cursor.forEach() implemented one way or another.

以下是一些示例:

collection.find(query).forEach(function(doc) {
  // handle
}, function(err) {
  // done or error
});

mongojs

db.collection.find(query).forEach(function(err, doc) {
  // handle
});

和尚

collection.find(query, { stream: true })
  .each(function(doc){
    // handle doc
  })
  .error(function(err){
    // handle error
  })
  .success(function(){
    // final callback
  });

猫鼬

collection.find(query).stream()
  .on('data', function(doc){
    // handle doc
  })
  .on('error', function(err){
    // handle error
  })
  .on('end', function(){
    // final callback
  });

.forEach回调内部更新文档

.forEach回调内部更新文档的唯一问题是,您不知道何时更新所有文档.

Updating documents inside of .forEach callback

The only problem with updating documents inside of .forEach callback is that you have no idea when all documents are updated.

要解决此问题,您应该使用一些异步控制流解决方案.以下是一些选项:

To solve this problem you should use some asynchronous control flow solution. Here are some options:

  • async
  • promises (when.js, bluebird)

以下是使用async的示例,该示例使用其 queue功能 :

Here is an example of using async, using its queue feature:

var q = async.queue(function (doc, callback) {
  // code for your update
  collection.update({
    _id: doc._id
  }, {
    $set: {hi: 'there'}
  }, {
    w: 1
  }, callback);
}, Infinity);

var cursor = collection.find(query);
cursor.each(function(err, doc) {
  if (err) throw err;
  if (doc) q.push(doc); // dispatching doc to async.queue
});

q.drain = function() {
  if (cursor.isClosed()) {
    console.log('all items have been processed');
    db.close();
  }
}

这篇关于如何使用Node.js在MongoDB中使用cursor.forEach()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆