在 Meteor 中使用一次调用将多个文档插入 mongodb

Inserting multiple documents into mongodb using one call in Meteor

在mongoshell中,可以insert an array of documents with one call。在 Meteor 项目中,我尝试使用

MyCollection = new Mongo.Collection("my_collection")
documentArray = [{"one": 1}, {"two": 2}]
MyCollection.insert(documentArray)

但是,当我从 mongo shell 检查 my_collection 时,它显示只插入了一个文档,并且该文档包含整个数组,就好像它已经被插入一样一张地图:

db.my_collection.find({})
{ "_id" : "KPsbjZt5ALZam4MTd", "0" : { "one" : 1 }, "1" : { "two" : 2} }

是否可以使用 Meteor 调用来一次性添加一系列文档,或者必须使用 here 中描述的技术?

我想在一次调用中插入多个文档会优化客户端的性能,新文档会同时可用。

您可以使用 bulk API 在服务器端进行批量插入。使用 forEach() 方法操作数组,并在循环内使用批量插入操作插入文档,这些操作是服务器顶部的简单抽象,可以轻松构建批量操作。

请注意,对于比 2.6 更旧的 MongoDB 服务器,API 将对操作进行下转换。然而,不可能 100% 下转换,因此可能存在一些无法正确报告正确数字的边缘情况。

您可以通过 Mongo.Collection

上的 rawCollectionrawDatabase 方法获得对 npm MongoDB 驱动程序中集合和数据库对象的原始访问
MyCollection = new Mongo.Collection("my_collection");

if (Meteor.isServer) {
    Meteor.startup(function () {
        Meteor.methods({
            insertData: function() {
                var bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp(),
                    counter = 0,
                    documentArray = [{"one": 1}, {"two": 2}];

                documentArray.forEach(function(data) {
                    bulkOp.insert(data);

                    counter++;
                    // Send to server in batch of 1000 insert operations
                    if (counter % 1000 == 0) {
                        // Execute per 1000 operations and re-initialize every 1000 update statements
                        bulkOp.execute(function(e, rresult) {
                            // do something with result
                        });
                        bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp();
                    }
                }); 

                // Clean up queues
                if (counter % 1000 != 0){
                    bulkOp.execute(function(e, result) {
                        // do something with result
                    });
                }
            }
        }); 
    });
}

我目前正在使用 mikowals:batch-insert 软件包。

您的代码只需稍作改动即可运行:

MyCollection = new Mongo.Collection("my_collection");
documentArray = [{"one": 1}, {"two": 2}];
MyCollection.batchInsert(documentArray);

我注意到的一个缺点是它不支持简单模式。