MongoDB Summary 05-update$set & $unset

Source: Internet
Author: User
Tags mongodb

Use $set to specify a value for a key, and if it does not exist, create it. This is useful for updating patterns or adding user definitions.

Db.user.insert ({"Name": "Codingwhy.com"})

This user now only has the name information and now needs to add an email to him

Db.user.update ({"Name": "Codingwhy.com"},{"$set": {"email": "Example@example.com"}})
{"_id": ObjectId (" 55092691591555a6c35dd698 ")," name ":" codingwhy.com "," email ":" Example@example.com "}

For example, now he has to add his personal hobbies, he may have a lot of hobbies, so hobbies should be an array

Db.user.update ({"Name": "Codingwhy.com"},{"$set": {"hobby": ["Swimming", "running", "Reading"]}})
{"_id": ObjectId ("55082691591555a6c35dd698"), "name": "codingwhy.com", "email": "example@example.com", "hobby": ["swimming", "Running", "reading"]}

If he doesn't have a hobby now ...

Db.user.update ({"Name": "Codingwhy.com"},{"$unset": {"hobby": 1}})
{"_id": ObjectId ("55082691591555a6c35dd698" ), "name": "codingwhy.com", "email": "Example@example.com"}

The hobby is gone ...

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.