- 写操作——添加操作
mongodb提供以下操作执行添加文档操作
- db.collection.insertOne() 3.2新添加
- db.collection.insertMany() 3.2 新添加
- db.collection.insert()
- 首先介绍下 insertone() 操作
语法规则:
db.collection.insertOne( <document>, { writeConcern: <document> //Optional. A document expressing the write concern. Omit to use the default write concern. } )
关于 writeconcern 后边章节会详细介绍
返回值:
A document containing:
- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
- A single element insertedId with the _id of the inserted document.
注意:
集合不存在该操作会创建集合。
该操作不支持 db.collection.explain() 查询计划 可以使用insert 代替。
实例:
try { db.products.insertOne( { item: "card", qty: 15 } ); }; catch (e) { print (e); };
返回值:
{ "acknowledged" : true, "insertedIds" : [ ObjectId("562a94d381cb9f1cd6eb0e1a"), ] }
添加write concern选项之后 复制集
try { db.products.insertOne( { "item": "envelopes", "qty": 100, type: "Self-Sealing" }, { writeConcern: { w : "majority", wtimeout : 100 } }; //w:majority,表示>1/2的节点有数据 ) } catch (e) { print (e); }
如果超时返回结果实例
WriteConcernError({ "code" : 64, "errInfo" : { "wtimeout" : true }, "errmsg" : "waiting for replication timed out" })
- 介绍下 inserMany() 操作 该操作是 3.2版本新添加的功能
语法规则:
db.collection.insertMany( { [ <document 1> , <document 2>, ... ] },//An array of documents to insert into the collection. 注意是数组 { writeConcern: <document>, ordered: <boolean> //Optional. A boolean specifying whether the mongod instance should perform an ordered or unordered insert. Defaults to true. 默认式按照顺序添加的 顺序添加的速度要慢于不按顺序添加的 } )
返回值:
A document containing:
- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled
- An array of _id for each successfully inserted documents
注意:
- 每一组操作最大可以有1000个文档。
- 顺序添加的速度要慢于不按顺序添加的。
- 不存在的集合会自动创建。
- insertMany() 也不支持db.collection.explain() 可以使用insert 代替。
- 如果添加出错会报出 BulkWriteError exception 异常,按照顺序添加的 操作遇到错误会直接停止,而不按照顺序的会继续执行在队列中的写操作。
实例:不指定 _id
try { db.products.insertMany( [ { item: "card", qty: 15 }, { item: "envelope", qty: 20 }, { item: "stamps" , qty: 30 } ] ); } catch (e) { print (e); }
返回值:
{ "acknowledged" : true, "insertedIds" : [ ObjectId("562a94d381cb9f1cd6eb0e1a"), ObjectId("562a94d381cb9f1cd6eb0e1b"), ObjectId("562a94d381cb9f1cd6eb0e1c") ] }
指定_id字段:
try { db.products.insertMany( [ { _id: 10, item: "large box", qty: 20 }, { _id: 11, item: "small box", qty: 55 }, { _id: 12, item: "medium box", qty: 30 } ] ); } catch (e) { print (e); }
返回值:
{ "acknowledged" : true, "insertedIds" : [ 10, 11, 12 ] }
插入一个_id字段重复的字段:
try { db.products.insertMany( [ { _id: 13, item: "envelopes", qty: 60 }, { _id: 13, item: "stamps", qty: 110 }, { _id: 14, item: "packing tape", qty: 38 } ] ); } catch (e) { print (e); }
返回值: 返回 BulkWriteError 异常 只会添加第一条数据
BulkWriteError({ "writeErrors" : [ { "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: restaurant.test index: _id_ dup key: { : 13.0 }", "op" : { "_id" : 13, "item" : "envelopes", "qty" : 60 } } ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
没有顺序添加操作:
try { db.products.insertMany( [ { _id: 10, item: "large box", qty: 20 }, { _id: 11, item: "small box", qty: 55 }, { _id: 11, item: "medium box", qty: 30 }, { _id: 12, item: "envelope", qty: 100}, { _id: 13, item: "stamps", qty: 125 }, { _id: 13, item: "tape", qty: 20}, { _id: 14, item: "bubble wrap", qty: 30} ], { ordered: false } ); } catch (e) { print (e); }
返回值: 即使出现错误后续的字段也能正常添加进
BulkWriteError({ "writeErrors" : [ { "index" : 2, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 11.0 }", "op" : { "_id" : 11, "item" : "medium box", "qty" : 30 } }, { "index" : 5, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 13.0 }", "op" : { "_id" : 13, "item" : "tape", "qty" : 20 } } ], "writeConcernErrors" : [ ], "nInserted" : 5, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
带着 写入安全级别writeconcern 跟 wtimeout
try { db.products.insertMany( [ { _id: 10, item: "large box", qty: 20 }, { _id: 11, item: "small box", qty: 55 }, { _id: 12, item: "medium box", qty: 30 } ], { w: "majority", wtimeout: 100 } ); } catch (e) { print (e); }
返回值: If the primary and at least one secondary acknowledge each write operation within 100 milliseconds
{ "acknowledged" : true, "insertedIds" : [ ObjectId("562a94d381cb9f1cd6eb0e1a"), ObjectId("562a94d381cb9f1cd6eb0e1b"), ObjectId("562a94d381cb9f1cd6eb0e1c") ] }
超时返回:
- WriteConcernError({ "code" : 64, "errInfo" : { "wtimeout" : true }, "errmsg" : "waiting for replication timed out" })
- 介绍下 inser() 操作
语法:
db.collection.insert( <document or array of documents>, //数组或者文档都可以添加 { writeConcern: <document>, ordered: <boolean> //跟insertMany()操作作用一致 } )
返回值:
- A WriteResult object for single inserts.
- A BulkWriteResult object for bulk inserts.
- 介绍下 批量操作 bulk 函数
将多个数据更新操作(插入 修改 删除)操作放到一个待执行的列表中来批量执行
包括: db.collection.initializeOrderedBulkOp() 顺序执行 如果其中某项操作出现问题 mongodb 不会做任何修改
db.collection.initializeUnorderedBulkOp() 并行执行
例如:如果一个执行list 包含添加 更新 删除操作 ,mongodb 会把操作分成三个组:第一个执行insert 操作 第二个执行更新操作 第三个执行删除操作
Bulk.getOperations()可以查看一组各类型的操作是如何分组的,执行之后才能调用。
BULK支持以下操作:
The Bulk() builder has the following methods: Name Description Bulk.insert() Adds an insert operation to a list of operations. Bulk.find() Specifies the query condition for an update or a remove operation. Bulk.find.removeOne() Adds a single document remove operation to a list of operations. Bulk.find.remove() Adds a multiple document remove operation to a list of operations. Bulk.find.replaceOne() Adds a single document replacement operation to a list of operations. Bulk.find.updateOne() Adds a single document update operation to a list of operations. Bulk.find.update() Adds a multi update operation to a list of operations. Bulk.find.upsert() Specifies upsert: true for an update operation. Bulk.execute() Executes a list of operations in bulk. Bulk.getOperations() Returns an array of write operations executed in the Bulk() operations object. Bulk.tojson() Returns a JSON document that contains the number of operations and batches in the Bulk() operations object. Bulk.toString() Returns the Bulk.tojson() results as a string.
详细信息查看 mongodb 文档
实例: 顺序执行操作 db.users.initializeOrderedBulkOp()
var bulk = db.users.initializeOrderedBulkOp(); bulk.insert( { user: "abc123", status: "A", points: 0 } ); bulk.insert( { user: "ijk123", status: "A", points: 0 } ); bulk.insert( { user: "mop123", status: "P", points: 0 } ); bulk.find( { status: "D" } ).remove(); bulk.find( { status: "P" } ).update( { $set: { comment: "Pending" } } ); bulk.execute();
实例:并行执行 db.collection.initializeUnorderedBulkOp() 执行操作的时候为了提升性能会重新更改执行的顺序。
var bulk = db.users.initializeUnorderedBulkOp(); bulk.insert( { user: "abc123", status: "A", points: 0 } ); bulk.insert( { user: "ijk123", status: "A", points: 0 } ); bulk.insert( { user: "mop123", status: "P", points: 0 } ); bulk.execute();
Bulk.getOperations() 返回mongodb bulk.execute() 执行时候的数组 包含执行的操作 。
实例:
var bulk = db.items.initializeUnorderedBulkOp(); for (var i = 1; i <= 1500; i++) { bulk.insert( { x: i } ); } bulk.execute(); bulk.getOperations();
返回的结果:
[ { "originalZeroIndex" : 0, "batchType" : 1, //1 insert 2 update 3 remove "operations" : [ { "_id" : ObjectId("53a8959f1990ca24d01c6165"), "x" : 1 }, ... // Content omitted for brevity { "_id" : ObjectId("53a8959f1990ca24d01c654c"), "x" : 1000 } ] }, { "originalZeroIndex" : 1000, "batchType" : 1, "operations" : [ { "_id" : ObjectId("53a8959f1990ca24d01c654d"), "x" : 1001 }, ... // Content omitted for brevity { "_id" : ObjectId("53a8959f1990ca24d01c6740"), "x" : 1500 } ] } ]