发布于 2015-09-14 14:51:08 | 174 次阅读 | 评论: 0 | 来源: 网络整理
The insert() method inserts a document or documents into a collection.
在 2.2 版更改: The insert() method can accept an array of documents to perform a bulk insert of the documents into the collection.
注解
For bulk inserts on sharded clusters, the getLastError command alone is insufficient to verify success. Applications should must verify the success of bulk inserts in application logic.
Consider the following behaviors of the insert() method:
The insert() method takes one of the following parameters:
参数: |
|
---|
Consider the following examples of the insert() method:
To insert a single document and have MongoDB generate the unique _id, omit the _id field in the document and pass the document to the insert() method as in the following:
db.products.insert( { item: "card", qty: 15 } )
This operation inserts a new document into the products collection with the item field set to card, the qty field set to 15, and the _id field set to a unique ObjectId:
{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }
注解
Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongod will add the _id field and generate the ObjectId.
To insert a single document, with a custom _id field, include the _id field set to a unique identifier and pass the document to the insert() method as follows:
db.products.insert( { _id: 10, item: "box", qty: 20 } )
This operation inserts a new document in the products collection with the _id field set to 10, the item field set to box, the qty field set to 20:
{ "_id" : 10, "item" : "box", "qty" : 20 }
注解
Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongod will add the _id field and generate the ObjectId.
To insert multiple documents, pass an array of documents to the insert() method as in the following:
db.products.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 } ] )
The operation will insert three documents into the products collection:
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("50631bc0be4617f17bb159ca"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("50631bc0be4617f17bb159cb"), "item" : "eraser", "qty" : 25 }