发布于 2015-09-14 14:55:42 | 153 次阅读 | 评论: 0 | 来源: 网络整理
The save() method updates an existing document or inserts a document depending on the parameter.
The save() method takes the following parameter:
参数: |
|
---|
Consider the following examples of the save() method:
Pass to the save() method a document without an _id field, so that to insert the document into the collection and have MongoDB generate the unique _id as in the following:
db.products.save( { item: "book", qty: 40 } )
This operation inserts a new document into the products collection with the item field set to book, the qty field set to 40, and the _id field set to a unique ObjectId:
{ "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }
注解
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.
Pass to the save() method a document with an _id field that holds a value that does not exist in the collection to insert the document with that value in the _id value into the collection, as in the following:
db.products.save( { _id: 100, item: "water", qty: 30 } )
This operation inserts a new document into the products collection with the _id field set to 100, the item field set to water, and the field qty set to 30:
{ "_id" : 100, "item" : "water", "qty" : 30 }
注解
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.
Pass to the save() method a document with the _id field set to a value in the collection to replace all fields and values of the matching document with the new fields and values, as in the following:
db.products.save( { _id:100, item:"juice" } )
This operation replaces the existing document with a value of 100 in the _id field. The updated document will resemble the following:
{ "_id" : 100, "item" : "juice" }