MongoDB common Operations--collection 3

Source: Internet
Author: User

1. Update the documents in the collection with the following syntax:

Db.collection.update (Criteria,objnew,upsert,multi)

Parameter description:
Criteria: The object used to set the query criteria
Objnew: An object for setting up updated content
Upsert: If the record already exists, update it, or add a record with a value of 0 or 1
Multi: If there are multiple records that match the criteria, whether they are all updated, the value is 0 or 1

Note: By default, only the first qualifying record is updated in general, the last two parameters are 0, 1, namely: Db.collection.update (criteria,objnew,0,1)

2. Update the document in the collection to change the document name User1 in the collection to name Jack

This modification has two problems, that is, the original document will be overwritten with the new document, if the original document has more than one key, the modification may be overwritten with only one key left. The second problem is that even if there are multiple documents that meet the update criteria, only the first qualifying record will be updated

3. Update the document in the collection, using the $inc to add 1 to the age of name User1 in the collection, the other keys are the same, $inc means that a key value is added minus the specified value

4. Update the document in the collection, $set the value used to specify a key, and if the key does not exist, create it.

For example:
To add an address to the document name User1, you can use the command:
Db.c1.update ({name: "user1"},{$set: {address: "BJ"}},0,1)

The document named User1 is modified to address TJ, the other key-value pairs are unchanged, and the command is:
Db.c1.update ({name: "user1"},{$set: {address: "TJ"}},0,1)

5. Update the document in the collection, $unset to delete a key

For example, if you delete the address key in a document named User1, you can use the command: Db.c1.update ({name: "user1"},{$unset: {address:1}},0,1)

MongoDB common Operations--collection 3

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.