在MongoDB节点Js中更新整个集合

时间:2020-02-15 08:02:13

标签: node.js mongodb mongoose

我有一个程序,在特定时间后会从FTP服务器接收 New 文件,我将新更新的文件数据插入数据库 MongoDB 中,这些字段保持不变,现在的问题是,每次我都必须将整个新集合插入数据库,并且集合会相应增加。示例-第一次数据是20条记录,第二次是40条,然后是60条,依此类推。我要做的是在插入新的 FILE 之前,先检查新文件中哪个字段的数据已更新数据,并且仅应更新数据库中这些字段的数据,而不是插入整个新文档。MONGOOSE或MONGODB是否为此提供解决方案,意味着如果我将数据作为参数传递,则它应该将我现有的收藏与我的新收藏进行比较数据,然后仅更新已更新的字段。.请帮助我,卡住了,谢谢:)。我正在使用 NODE JS ...

var c = new Client();
            var connectionProperties = {
                host: 'ABC',
                user: 'ABC',
                port: 'ABC',
                password: 'ABC',
            };
            c.connect(connectionProperties);
          c.on('ready', function () {
                c.get('path-to-excel-file', function (err, stream) {
                    if (err) throw err;
                    stream.once('close', function () {
                        const workBook = XLSX.readFile('Convertedfile.xlsx');
                        XLSX.writeFile(workBook, 'Convertedfile', { bookType: "csv" });
                        csv()
                            .fromFile("Convertedfile")
                            .then((jsonObj) => {
                                Model.collection.insert(jsonObj, function (err, docs) {
                                    if (err) {
                                        return console.error(err);
                                    } else {
                                        console.log("All Documents insterted");
                                    }
                                });
                            })
                        c.end()
                    });
                    stream.pipe(fs.createWriteStream('ConvertedFile.xlsx'))
                })
          })

1 个答案:

答案 0 :(得分:0)

您似乎需要 upsert 表示是否存在文档/记录或插入/创建它。

因此,这一次可以一次完成一个文档,也可以批量进行,但是需要先查询才能找到匹配的文档。

由于您未提供任何示例数据,因此我无法为您编写示例代码段,但是以下是用于入门的链接:批量访问Bulk.find.upsert,对于单个文档,此线程很不错:how-do-i-update-upsert-a-document-in-mongoose

更新:以下是正在运行的mongodb批量更新:

const mongo = require('mongodb');
const MongoClient = mongo.MongoClient;

const client = new MongoClient('mongodb://127.0.0.1:27017', { useUnifiedTopology: true });
client.connect(async err => {
    if (err) {
        console.log('DB Connection Error ', err);
    } else {
        const db = client.db('node-cheat-db');

        // lets assume you've read all file contents and data is now ready for db operation
        let records = [
            {first: 'john', last: 'doe', email: 'johen@doe.com'},
            {first: 'jack', last: 'doe', email: 'jack@doe.com'},
            {first: 'jill', last: 'doe_updated', email: 'jill@doe.com'}
        ];

        // prepare bulk upsert so that new records are created and existing are updated
        let bulk = db.collection('users').initializeOrderedBulkOp();
        for (var i = 0; i < records.length; i++) {
            bulk.find({
        "email": records[i].email // at least 1 key should be treated as PK; in this example email is PK
        }).upsert(records[i]).replaceOne(records[i]);
        }
        bulk.execute(function (err,updateResult) {
                if (updateResult.result.ok != 1) {
                    console.log('Bulk Upsert Error');
                } else {
                    console.log(`Inserted: ${updateResult.result.nUpserted} and Updated: ${updateResult.result.nModified}`);
                }
        });
    }
});

示例输出如下:

已插入:0,已更新:3

更多详细信息:

克隆节点作弊bulk-update,先运行node bulk-update.js,然后运行npm install mongodb