mongodb3.2系統性學習——1、文檔插入insert() insertOne() insertMany() Bulk操作


  • 寫操作——添加操作

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

注意:

  1. 每一組操作最大可以有1000個文檔。
  2. 順序添加的速度要慢於不按順序添加的。
  3. 不存在的集合會自動創建。
  4. insertMany() 也不支持db.collection.explain() 可以使用insert 代替
  5. 如果添加出錯會報出 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()操作作用一致
   }
)

 

返回值:

       將多個數據更新操作(插入 修改 刪除)操作放到一個待執行的列表中來批量執行

    包括:      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 }
      ]
   }
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM