Why use modifiers?
Usually we only modify part of the document, it is cumbersome to update the entire document, usually through an atomic update modifier.
1. "$set" modifier
"$set" is used to specify a field that is created if it does not exist. This is very convenient for some updates or additions.
Such as:
Step1: As long as a data to the users database, through JavaScript to complete:
var logs={name: "Joe", Age:30,sex: "Female", Location: "Wisconsin"}
Logs
Run:
1 /*1*/2 {3 "name":"Joe",4 " Age":30.0,5 "Sex":"female",6 " Location":"Wisconsin"7}
Step2: Put into the users database
Db.users.insert (Logs)
Query Result:
Db.users.find ()
/*1*/{ "_id": ObjectId ("575a2acfbc9fb3f12145a004"), "name":"Joe", " Age":30.0, "Sex":"female", " Location":"Wisconsin"}
Step3: Join to insert a favorite book:
Db.users.update ({name: "Joe"},{"$set": {"Favorite book": "War and Peace"}})
Then query Db.users.find ()
/*1*/{ "_id": ObjectId ("575a2acfbc9fb3f12145a004"), "name":"Joe", " Age":30.0, "Sex":"female", " Location":"Wisconsin", "Favorite Book":"War and Peace"}
From the results we can see that a favorite book field has been added to the data to achieve the results we want ^_^;
Step4: If Joe likes another book, continue to see how "$set" is going to be a big fan.
/*1*/{ "_id": ObjectId ("575a2acfbc9fb3f12145a004"), "name":"Joe", " Age":30.0, "Sex":"female", " Location":"Wisconsin", "Favorite Book":"Forrest Gump"}
"$Set" can also modify the type of the key, for example, like a lot of books, you can put in the array.
As follows:
Db.users.update ({name: "Joe"},{"$set": {"Favorite book": ["Cat ' s Cradle", "Foundation Trilogy", "Ender ' Game"]})
/*1*/{ "_id": ObjectId ("575a2acfbc9fb3f12145a004"), "name":"Joe", " Age":30.0, "Sex":"female", " Location":"Wisconsin", "Favorite Book" : [ "Cat ' s Cradle", "Foundation Trilogy", "Ender ' s Game" ]}
You can also delete a field by using "$unset"
Db.users.update ({name: "Joe"},{"$unset": {"Favorite book": 1}})
/*1*/{ "_id": ObjectId ("575a2acfbc9fb3f12145a004"), "name":"Joe", " Age":30.0, "Sex":"female", " Location":"Wisconsin"}
This is the same as the beginning.
"$set" can also modify an inline document
Such as:
var log={title: "A Blog Post", Content: "...", Author:{name: "Joe", Email: "[email protected]"}
Log
Db.blog.posts.insert (log)
Db.blog.posts.findOne ()
/*1*/{ "_id": ObjectId ("575a313fbc9fb3f12145a008"), "title":"A Blog Post", "content":"...", "author" : { "name":"Joe", "Email":"[email protected]" }}
Db.blog.posts.update ({"Author.name": "Joe"},{"$set": {"Author.name": "Joe Mather"}})
/*1*/{ "_id": ObjectId ("575a313fbc9fb3f12145a008"), "title":"A Blog Post", "content":"...", "author" : { "name":"Joe Mather", "Email":"[email protected]" }}
Summary: The modifier that begins with the $ starts with the primary key to modify the corresponding content.
Use of MongoDB modifier 1