MongoDB 3 ways to insert data _mongodb

Source: Internet
Author: User
Tags mongodb mongodb add


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}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.