db.collection.insertOne() |
插入单条文档到集合中
|
db.collection.insertMany() |
插入多条文档到集合中 |
db.collection.insert() |
插入单条或多条文档到集合中
|
db.collection.insertOne( <document>, { writeConcern: <document> } )
只能传一个文档,不能是数组
db.collection.insertMany( [ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )
必传一个数组,即使是空数组
db.collection.insert( <document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )
可以传单条文档或者文档数组
看着是一种出错捕捉机制,搞清楚要干嘛再更新吧
// 插入单条文档 > db.test.insert({}) WriteResult({ "nInserted" : 1 }) // 插入多条文档 > db.test.insert([]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
db.test.insert( { item : "card", qty : 15 })
MongoDB 会自动给它分配一个 _id
db.test.find() { "_id" : ObjectId("60b4e2eeec0fd33d89e97a98"), "item" : "card", "qty" : 15 }
这些 Objectld 值与执行操作时的机器和时间有关
值 _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 } ] )
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 会继续将其余文档插入数组中
原文:https://www.cnblogs.com/poloyy/p/14747861.html