猫鼬(mongodb)批量插入?

Geu*_*uis 109 mongoose mongodb node.js

请问猫鼬V3.6 +支持批量插入呢?我已经搜索了几分钟,但是这个查询的任何内容都是几年前的答案,答案是明确的.

编辑:

为了将来参考,答案是使用Model.create().create()接受一个数组作为其第一个参数,因此您可以将文档作为数组插入.

请参见Model.create()文档

Luc*_*iva 152

Model.create()vs Model.collection.insert():一种更快的方法

Model.create()如果你处理的是非常大的批量,那么插入是一种糟糕的方法.这将是非常缓慢的.在这种情况下你应该使用Model.collection.insert,它表现得更好.根据批量的大小,Model.create()甚至会崩溃!试过一百万份文件,没有运气.使用Model.collection.insert它只需几秒钟.

Model.collection.insert(docs, options, callback)
Run Code Online (Sandbox Code Playgroud)
  • docs 是要插入的文档数组;
  • options是一个可选的配置对象 - 请参阅文档
  • callback(err, docs)将在保存所有文档或发生错误后调用.成功时,docs是持久化文档的数组.

正如Mongoose的作者在这里指出的,这种方法将绕过任何验证程序并直接访问Mongo驱动程序.这是你必须要做的权衡,因为你正在处理大量的数据,否则你根本无法将它插入你的数据库(请记住我们在这里谈论成千上万的文档).

一个简单的例子

var Potato = mongoose.model('Potato', PotatoSchema);

var potatoBag = [/* a humongous amount of potato objects */];

Potato.collection.insert(potatoBag, onInsert);

function onInsert(err, docs) {
    if (err) {
        // TODO: handle error
    } else {
        console.info('%d potatoes were successfully stored.', docs.length);
    }
}
Run Code Online (Sandbox Code Playgroud)

参考

  • 由于`Model.collection`直接通过Mongo驱动程序,你会失去所有整洁的猫鼬东西,包括验证和钩子.请记住一些事情.`Model.create`丢失了钩子,但仍然经过验证.如果你想要它,你必须迭代并且`new MyModel()` (13认同)

Der*_*rek 110

Mongoose 4.4.0现在支持批量插入

Mongoose 4.4.0引入了--true--使用模型方法进行批量插入.insertMany().它比循环.create()或提供数组更快.

用法:

var rawDocuments = [/* ... */];

Book.insertMany(rawDocuments)
    .then(function(mongooseDocuments) {
         /* ... */
    })
    .catch(function(err) {
        /* Error handling */
    });
Run Code Online (Sandbox Code Playgroud)

要么

Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
Run Code Online (Sandbox Code Playgroud)

你可以跟踪它:

  • 这与`bulkWrite`有什么不同?请参见此处:http://stackoverflow.com/questions/38742475/what-is-the-right-approach-to-update-many-records-in-mongodb-using-mongoose/38743353#38743353 (3认同)
  • 目前,此方法不支持选项. (2认同)

ben*_*ske 23

的确,你可以使用Mongoose的"create"方法,它可以包含一个文件数组,请看这个例子:

Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});
Run Code Online (Sandbox Code Playgroud)

回调函数包含插入的文档.您并不总是知道必须插入多少项(固定参数长度如上),因此您可以循环它们:

var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
    insertedDocs.push(arguments[i]);
}
Run Code Online (Sandbox Code Playgroud)

更新:更好的解决方案

一个更好的解决方案是使用Candy.collection.insert()而不是Candy.create()- 在上面的例子中使用 - 因为它更快(create()调用Model.save()每个项目所以它更慢).

有关更多信息,请参阅Mongo文档:http: //docs.mongodb.org/manual/reference/method/db.collection.insert/

(感谢arcseldon指出这一点)

  • 那么这是一个糟糕的命名选择,因为`type`通常在Mongoose中保留用于命名数据​​库对象的ADT. (2认同)
  • @sirbenbenji我改变了它,但它也是官方文档中的一个例子.我认为没有必要为此投票. (2认同)

Arp*_*pit 6

这里有两种使用 insertMany 和 save 保存数据的方法

1) MongooseinsertMany批量保存文档数组

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */
router.post('/addDocuments', function (req, res) {
    const data = [/* array of object which data need to save in db */];

    Potato.insertMany(data)  
    .then((result) => {
            console.log("result ", result);
            res.status(200).json({'success': 'new documents added!', 'data': result});
    })
    .catch(err => {
            console.error("error ", err);
            res.status(400).json({err});
    });
})
Run Code Online (Sandbox Code Playgroud)

2) Mongoose 保存文档数组 .save()

这些文件将并行保存。

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */
router.post('/addDocuments', function (req, res) {
    const saveData = []
    const data = [/* array of object which data need to save in db */];
    data.map((i) => {
        console.log(i)
        var potato = new Potato(data[i])
        potato.save()
        .then((result) => {
            console.log(result)
            saveData.push(result)
            if (saveData.length === data.length) {
                res.status(200).json({'success': 'new documents added!', 'data': saveData});
            }
        })
        .catch((err) => {
            console.error(err)
            res.status(500).json({err});
        })
    })
})
Run Code Online (Sandbox Code Playgroud)


SUN*_*N K 5

您可以使用插入数组中的值来使用mongoDB shell执行批量插入.

db.collection.insert([{values},{values},{values},{values}]);
Run Code Online (Sandbox Code Playgroud)


dde*_*nis 5

看来使用mongoose有超过1000个文档的限制,当使用

Potato.collection.insert(potatoBag, onInsert);
Run Code Online (Sandbox Code Playgroud)

您可以使用:

var bulk = Model.collection.initializeOrderedBulkOp();

async.each(users, function (user, callback) {
    bulk.insert(hash);
}, function (err) {
    var bulkStart = Date.now();
    bulk.execute(function(err, res){
        if (err) console.log (" gameResult.js > err " , err);
        console.log (" gameResult.js > BULK TIME  " , Date.now() - bulkStart );
        console.log (" gameResult.js > BULK INSERT " , res.nInserted)
      });
});
Run Code Online (Sandbox Code Playgroud)

但在使用 10000 个文档进行测试时,速度几乎是原来的两倍:

function fastInsert(arrOfResults) {
var startTime = Date.now();
    var count = 0;
    var c = Math.round( arrOfResults.length / 990);

    var fakeArr = [];
    fakeArr.length = c;
    var docsSaved = 0

    async.each(fakeArr, function (item, callback) {

            var sliced = arrOfResults.slice(count, count+999);
            sliced.length)
            count = count +999;
            if(sliced.length != 0 ){
                    GameResultModel.collection.insert(sliced, function (err, docs) {
                            docsSaved += docs.ops.length
                            callback();
                    });
            }else {
                    callback()
            }
    }, function (err) {
            console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved  " , docsSaved, " DIFF TIME:",Date.now() - startTime);
    });
}
Run Code Online (Sandbox Code Playgroud)