Docs HomeMongoDB Manual

Bulk.insert()

Tip

Starting in version 3.2, MongoDB also provides the db.collection.bulkWrite() method for performing bulk write operations.从3.2版本开始,MongoDB还提供了db.collection.bulkWrite()方法来执行批量写入操作。

Description描述

Bulk.insert(<document>)

Adds an insert operation to a bulk operations list.将插入操作添加到批量操作列表中。

Bulk.insert() accepts the following parameter:接受以下参数:

Parameter参数Type类型Description描述
docdocumentDocument to insert. 要插入的文档。The size of the document must be less than or equal to the maximum BSON document size.文档的大小必须小于或等于BSON文档的最大大小

Behavior行为

Insert Inaccuracies插入不准确

Even if you encounter a server error during an insert, some documents may have been inserted.即使在插入过程中遇到服务器错误,也可能已插入某些文档。

After a successful insert, the system returns BulkWriteResult.nInserted, the number of documents inserted into the collection. If the insert operation is interrupted by a replica set state change, the system may continue inserting documents. 成功插入后,系统返回BulkWriteResult.nInserted,即插入集合的文档数。如果插入操作因副本集状态更改而中断,系统可以继续插入文档。As a result, BulkWriteResult.nInserted may report fewer documents than actually inserted.因此,BulkWriteResult.nInserted可能报告的文档数少于实际插入的文档数。

Example实例

The following initializes a Bulk() operations builder for the items collection and adds a series of insert operations to add multiple documents:下面初始化items集合的Bulk()操作生成器,并添加一系列插入操作以添加多个文档:

var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
bulk.execute();