$push: Adds an element to the document array, or automatically adds an array if there is no array.
db.users.insert({"name":"zhang"})
db.users.update({"name":"zhang"},{"$push":{"emails":"[email protected]"}})
db.users.update({"name":"zhang"},{"$push":{"emails":"[email protected]"}})
The above code, first create the name of the user Zhang, and then to the user to join the mailbox, put into the emails array.
$addToSet: The function is the same as $push, except that $addToSet think of the array as a set, and if the same element exists in the array, it will not be inserted.
db.users.update({"name":"zhang"},{"$addToSet":{"emails":"[email protected]"}})
db.users.find()
You can see that there are no two [email protected] mailboxes.
$addToSet can also be used in combination with $each to add multiple values at once.
db.users.update({"name":"zhang"},{"$addToSet":{"emails":{"$each":["[email protected]","[email protected]","[email protected]"]}}})
$pop, relative to $push, delete the elements in the array
db.users.update({"name":"zhang"},{"$pop":{"emails":{key:1}}});
Key=1, delete from tail, key=-1, delete from scratch
$pull Delete the specified element, in conjunction with the above example, delete the specified mailbox
db.users.update({"name":"zhang"},{"$pull":{"emails":"[email protected]"}});
Modifies the element at the specified location:
Each element of the array has an index, starting with 0. After a series of actions above, the documentation for Zhang should look like this:
{ "_id" : ObjectId("51a16b02d2ded250f4aab338"), "emails" : [ "[email protected]", "[email protected]" ], "name" : "zhang" }
If you want to change the first mailbox to [email protected]:
db.users.update({"name":"zhang"},{"$set":{"emails.0":"[email protected]"}});
If you want to replace [email protected] with [email protected], when you do not know the [email protected] Index:
db.users.update({"name":"zhang","emails":"[email protected]"},{"$set":{"emails.$":"[email protected]"}});
MongoDB Array Manipulation