$ Push: add an element to the document array. If this array is not available, the array is automatically added.
The code is as follows: |
Copy code |
Db. users. insert ({"name": "zhang "}) Db. users. update ({"name": "zhang" },{ "$ push": {"emails": "zhang@pocketdigi.com "}}) Db. users. update ({"name": "zhang" },{ "$ push": {"emails": "zhang@fwvga.com "}}) |
The above code first creates a user named zhang, then adds the user to the mailbox, and puts it in the emails array.
$ AddToSet: The function is the same as $ push. The difference is that $ addToSet treats an array as a Set. If the array contains the same elements, it is not inserted.
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang" },{ "$ addToSet": {"emails": "zhang@fwvga.com "}}) Db. users. find () |
As you can see, there are no mailboxes for two zhang@fwvga.com.
$ AddToSet can also be used in combination with $ each to add multiple values at a time.
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang" },{ "$ addToSet": {"emails": {"$ each": ["zhang@fwvga.com", "zhang@163.com ", "zhang@qq.com"] }}) |
$ Pop, corresponding to $ push, deletes elements in the array
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang" },{ "$ pop": {"emails" :{ key: 1 }}}); |
Key = 1, delete from the end, key =-1, delete from the beginning
$ Pull deletes a specified element. In combination with the preceding example, it deletes the specified email address.
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang" },{ "$ pull": {"emails": "zhang@163.com "}}); |
Modify the element at the specified position:
Each element of the array has an index, starting from 0. After a series of operations above, zhang's document should be as follows:
The code is as follows: |
Copy code |
{"_ Id": ObjectId ("51a16b02d2ded250f4aab338"), "emails": ["zhang@pocketdigi.com", "zhang@fwvga.com"], "name": "zhang "} |
If you want to change the first mailbox to a zhang@163.com:
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang" },{ "$ set": {"emails.0": "zhang@163.com "}}); |
If you want to replace the zhang@fwvga.com with a zhang@qq.com, when you do not know the zhang@fwvga.com index:
The code is as follows: |
Copy code |
Db. users. update ({"name": "zhang", "emails": "zhang@fwvga.com" },{ "$ set": {"emails. $ ":" zhang@qq.com "}}); |