插入方法
db.collection.insertOne()
|
插入單條文檔到集合中
|
db.collection.insertMany()
|
插入多條文檔到集合中
|
db.collection.insert()
|
插入單條或多條文檔到集合中
|
insertOne() 語法格式
db.collection.insertOne( <document>, { writeConcern: <document> } )
只能傳一個文檔,不能是數組
insertMany() 語法格式
db.collection.insertMany( [ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )
必傳一個數組,即使是空數組
insert() 語法格式
db.collection.insert( <document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )
可以傳單條文檔或者文檔數組
writeConcern
看着是一種出錯捕捉機制,搞清楚要干嘛再更新吧
ordered
- true:對數組中的文檔執行有序插入,其中一個文檔發生錯誤,MongoDB 將返回而不處理數組中的其余文檔(默認)
- false:無序插入,其中一個文檔發生錯誤,則繼續處理數組中的其他文檔
三種 insert 方法的返回內容
// 插入單條文檔 > db.test.insert({}) WriteResult({ "nInserted" : 1 }) // 插入多條文檔 > db.test.insert([]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
插入操作的重點知識
- MongoDB 向集合里插入記錄時,無須事先對數據存儲結構進行定義,每個文檔的數據結構都可以是不同的
- 如果待插入的集合不存在,則插入操作會默認創建集合
- MongoDB 中,插入操作以單個集合為目標
- MongoDB 中的所有寫入操作都是單個文檔級別的原子操作
插入不指定 _id 字段的文檔
db.test.insert( { item : "card", qty : 15 })
MongoDB 會自動給它分配一個 _id
db.test.find() { "_id" : ObjectId("60b4e2eeec0fd33d89e97a98"), "item" : "card", "qty" : 15 }
這些 Objectld 值與執行操作時的機器和時間有關
插入指定 _id 字段的文檔
值 _id 必須在集合中唯一,以避免重復鍵錯誤
db.test.insert( { _id: 10, item: "box", qty: 20 } ) db.test.find() { "_id" : 10, "item" : "box" , "qty": 20 }
可以看到新插入文檔的 id 值為設置的 id 值
插入文檔數組
插入的多個文檔無須具有相同的字段
db.test1.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" }, { item: "pen", qty: 20 }, { item: "eraser", qty: 25 } ] )
- 的第一個文檔包含一個 _id 字段和一個 type 字段
- 第二個和第三個文檔不包含 _id 字段
- 因此,在插入過程中,MongoDB 將會為第二個和第三個文檔創建默認 _id 字段
db.test1.find() { "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" } { "_id" : ObjectId("60b4e98fec0fd33d89e97a99"), "item" : "pen", "qty" : 20 } { "_id" : ObjectId("60b4e98fec0fd33d89e97a9a"), "item" : "eraser", "qty" : 25 }
無序插入
db.products.insert( [ { _id: 20, item: "lamp", qty: 50, type: "desk" }, { _id: 21, item: "lamp", qty: 20, type: "floor" }, { _id: 22, item: "bulk", qty: 100 } ], { ordered: false } )
如果在插入其中一個文檔期間發生錯誤,MongoDB 會繼續將其余文檔插入數組中
還有其他插入文檔的方法
需要添加 upsert: true 選項
db.collection.update()
db.collection.updateOne()
db.collection.updateMany()
db.collection.findAndModify()
db.collection.findOneAndUpdate()
db.collection.findOneAndReplace()
不需要添加也可以插入文檔
db.collection.save()
db.collection.bulkWrite()