Insert () Method:
The following is a document that inserts a three field into the inventory collection:
Copy Code code as follows:
Db.inventory.insert ({_id:10, type: "Misc", Item: "Card", qty:15})
In the real example, the document has a user-specified _id field with a value of 10, which must be unique in the inventory collection.
Update () method:
Call the update () method to create a new document using the UPSERT flag when there are no documents matching the query criteria. The following example creates a new document when a document with {type: "Books", Item: "Journal"} is not included in the inventory collection:
Copy Code code as follows:
Db.inventory.update (
{type: ' book ', Item: ' Journal '},
{$set: {qty:10}},
{Upsert:true}
)
MongoDB Add the _id field and assign a unique objectid as its value. The new document contains the item and type fields from the query <query> criteria, and the Qty field from the update <update> parameter:
Copy Code code as follows:
{"_id": ObjectId ("51e8636953dbe31d5f34a38a"), "Item": "Journal", "Qty": Ten, "Type": "Book"}
Save () method:
Use the Save () method to insert a document that saves a document that does not contain the _id field, or a document that contains a _ID field but the field value does not exist in the collection. The following example creates a new document in the inventory collection:
Copy Code code as follows:
Db.inventory.save ({type: "book", Item: "Notebook", qty:40})
MongoDB Add the _id field and assign a unique objectid as its value.
Copy Code code as follows:
{"_id": ObjectId ("51E866E48737F72B32AE4FBC"), "type": "Book", "Item": "Notebook", "qty": 40}