答案取决于你使用的驱动程序.我知道的所有MongoDB驱动程序都以这种或那种方式实现了cursor.forEach()
个.
以下是一些例子:
collection.find(query).forEach(function(doc) {
// handle
}, function(err) {
// done or error
});
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
callback在.forEach
回调中更新文档的唯一问题是,您不知道何时更新所有文档.
要解决这个问题,您应该使用一些异步控制流解决方案.以下是一些选项:
下面是使用async
的一个例子,使用它的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();
}
}