栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Node.js将许多记录插入Mongodb的正确方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Node.js将许多记录插入Mongodb的正确方法

如果您的MongoDB服务器是2.6或更高版本,最好利用写命令 Bulk
API

来执行大容量插入操作,这些操作只是服务器顶部的抽象,以便于构建大容量操作,并且因此,随着您对大型馆藏的更新,性能会有所提高。

批量发送批量插入操作会减少服务器的流量,从而通过不发送所有单独语句中的所有内容,而是将其拆分为可管理的大块来进行服务器承诺,从而执行高效的有线交易。使用这种方法,也减少了在回调中等待响应的时间。

这些批量操作主要有两个方面:

  • 有序批量操作 。这些操作按顺序执行所有操作,并在第一个写入错误时出错。
  • 无序批量操作 。这些操作并行执行所有操作,并汇总所有错误。无序批量操作不能保证执行顺序。

请注意,对于低于2.6的旧服务器,API将下转换操作。但是,不可能将100%下变频,因此在某些极端情况下无法正确报告正确的数字。

在您的情况下,您可以批量执行批量API插入操作,如下所示:

对于MongoDB 3.2+, 使用

bulkWrite

var MongoClient = require('mongodb').MongoClient;var url = 'mongodb://localhost:27017/test';var entries = [ ... ] // a huge array containing the entry objectsvar createNewEntries = function(db, entries, callback) {    // Get the collection and bulk api artefacts    var collection = db.collection('entries'),       bulkUpdateOps = [];    entries.forEach(function(doc) {        bulkUpdateOps.push({ "insertOne": { "document": doc } });        if (bulkUpdateOps.length === 1000) { collection.bulkWrite(bulkUpdateOps).then(function(r) {     // do something with result }); bulkUpdateOps = [];        }    })    if (bulkUpdateOps.length > 0) {        collection.bulkWrite(bulkUpdateOps).then(function(r) { // do something with result        });    }};

对于MongoDB <3.2

var MongoClient = require('mongodb').MongoClient;var url = 'mongodb://localhost:27017/test';var entries = [ ... ] // a huge array containing the entry objectsvar createNewEntries = function(db, entries, callback) {    // Get the collection and bulk api artefacts    var collection = db.collection('entries'),       bulk = collection.initializeOrderedBulkOp(), // Initialize the Ordered Batch        counter = 0;    // Execute the forEach method, triggers for each entry in the array    entries.forEach(function(obj) {        bulk.insert(obj);        counter++;        if (counter % 1000 == 0 ) { // Execute the operation bulk.execute(function(err, result) {       // re-initialise batch operation     bulk = collection.initializeOrderedBulkOp();     callback(); });        }    });    if (counter % 1000 != 0 ){        bulk.execute(function(err, result) { // do something with result  callback();          });     } };

调用该

createNewEntries()
函数。

MongoClient.connect(url, function(err, db) {    createNewEntries(db, entries, function() {        db.close();    });});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/595005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号