如何循环MongoDB收集并一个接一个地处理文档?

时间:2018-12-31 18:51:22

标签: node.js mongodb

我想循环一个MongoDB集合并逐个处理每个文档。如果该文档符合特定条件,我将更新该文档以将其标记为“已处理”,然后基于该文档插入或更新另一个集合。

这是我的代码,但是不起作用:

$$ROOT

请注意: 我不是在寻找总体分辨率。

先谢谢了。

Richard Xu

1 个答案:

答案 0 :(得分:0)

首先,您的代码的条件有误,应该是==而不是=

就一次处理1个文档而言,我建议使用async库来满足此类需求。

这里是如何将代码转换为使用异步库的示例

const async = require('async')
db.Chapter2.find({}, function(err, docs) {
    // docs is a collection of all of our documents, now we can use async.forEach to loop through them
    async.forEach(docs, function(doc, callback) {
        var processed = true;

        // doc is our current item in this collection, everytime we are done with it we would use callback so our loop moves on

        // Since you already have the doc on hand there is no need to call `update` you can just alter values and call `save`
        doc.processed = processed 

        // I suggest Author is an index in this collection to optimize it
        count = db.authors.find({ "Author": doc.Author });

        if ( count == 0) {
              db.authors.insertOne({Author: doc.Author, count: 1});
        } else {
              db.authors.updateOne({Author: doc.Author, {$set: {count: count +1}});
        }
        doc.save(function(err) {
           // In order for us to move to the next item we need to callback
           // the first argument is an error so here we simply check
           // If there is an error then callback with error otherwise without
           err ? callback(err) : callback(null)
        })

    }, function(err){
        // The loop is completed
        if (err) {
           // But there was an error handle it here
        } else {
           // The loop completed successfully
        }
    })
})

此答案可以进一步优化。但这应该可以解决您的问题

编辑:如果此值从未更改,我不确定为什么会有var processed = true。只需设置doc.processed = true