Insert and save a document
Insert a document using the Insert method for the target set:
> Db.foo.insert ({"Bar": "Baz"})
This will add a "_id" key to the document (if it is not) and then save it to MongoDB.
BULK INSERT
If you are inserting multiple documents, using BULK INSERT is faster. Bulk INSERT passes a document-formed array to the database.
If you are importing data only (for example, from a data feed or from MySQL), you can use command-line tools such as Mongoimport instead of bulk INSERT.
Delete a document
> Db.users.remove ()
The above actions extend all the documents in the Users collection. However, the collection itself is not deleted, and the original index is retained.
The Remove function can accept a query document as an optional parameter. After this parameter is given, only documents that meet the criteria are deleted. Included, suppose to delete all "Out-put" in the Mailing.list collection as true:
> Db.mailing.list.remove ({"Opt-out": true})
Deleting data is permanent, cannot be undone, and cannot be recovered.
Delete Speed
Deleting a document is usually quick, but it is faster to clear the entire collection, delete it directly (and then rebuild the index).
For example, in Python, 1 million virtual elements are inserted using the following method:
For I in Range (1000000):
Collection.insert ({"foo": "Bar", "baz": I, "Z": 10-i})
Now delete the document you just inserted and record the time spent. Let's start with a simple delete (remove):
Import Time from Import = = = = Time.time ()-Start print "%d seconds " % Total
This script outputs "46.08 seconds"
If you use Db.drop_collection ("bar") instead of remove and find_one, it only takes. 01 seconds, the speed increase is quite obvious.
Update document
Ⅰ use the Update method to modify the documents that are stored in the database. Update has two parameters, one is to query the document, to find the required document, and the other is a modifier (modifier) document, which describes what changes to the modified document.
Cases:
> Joe = Db.people.findOne ({"Name": "Joe", "Age": 20})
> joe.age++;
> db.people.update ({"Name": "Joe"}, Joe)
Ⅱ using modifiers
Usually the document will only have a part to be updated. Using an atomic update modifier makes this part of the update extremely funny. The update modifier is a special key that specifies complex update operations, such as resizing, adding, or deleting keys, and possibly manipulating arrays or inline documents.
Suppose you want to prevent a Web site from analyzing data in a collection, and whenever someone accesses a page, it increments the counter. You can use the update modifier atomically to accomplish this increase. The number of accesses for each URL is stored in the document in the following way:
{
"_id": ObjectId ("4b253b067525f35f94b60a31"),
"url": "www.example.com",
"Pageviews": 52
}
Each time someone accesses it, it finds the page through a URL and adds a value of "pageviews" to the "$inc" modifier.
> db.analytics.update ({"url": "www.example.com"}, {"$inc": {"pageviews": 1}})
Then, a find operation is performed, and the value of "pageviews" is increased by 1.
> Db.analytics.find ()
{
"_id": ObjectId ("4b253b067525f35f94b60a31"),
"url": "www.example.com",
"Pageviews": 53
}
① "$set" modifier
"$set" is used to specify a value for a key. If the key does not exist, it is created.
Example: Add favorite books to user information:
> db.users.update ({"_id": ObjectId ("4b253b067525f35f94b60a31")}, {"$set": {"Favorite book": "War And Peace"}})
If the user feels like another book:
> db.users.update ({"Name": "Joe"}, {"$set": {"Favorite book": "Green Eggs and Ham"}})
Use "$set" to modify the data type of the key. For example, if a user likes a bunch of books:
> db.users.update ({"Name": "Joe"}: {"$set": {"Favorite book": ["Cat ' s Cradle", "Fundation Trilogy", "Ender's Game"] }})
If users find that they do not love reading, you can use the "$unset" to remove the key completely:
> db.users.update ({"Name": "Joe"}, {"$unset": {"Favorite book": 1}})
② Increase and decrease
> Db.game.update ({"Game": "Pinball", "User": "Joe"}, {"$inc": {"score": 50}})
③ array modifier
If the specified key does not exist, "$push" adds an element to the end of the existing array and creates a new array if it does not.
For example, suppose you want to store a blog post to add a "comments" (comment) key that contains an array. You can push a comment to a "comments" array that does not yet exist, and the array is automatically created and added to the comment:
> db.blog.posts.update ({"title": "A blog post"}, {$push: {"comments": {"name": "Joe", "email": "[email protected]" , "content": "nice post."}})
If you want to add a comment, you can then use the "$push".
This is often the case, if a value is not in the array, add it. You can do this in the query document by using "$ne". For example, if you sit and no longer add to the list of citations, you can do this:
> db.papers.update ({"Authors cited": {"$ne": "Richie"}}, {$push: {"authors cited": "Richie"}})
You can also do the same thing with "$addToSet", and "$addToSet" can avoid repetition.
> db.users.update ({"_id": ObjectId ("4b2d75476cc613d5ee930164")}, {"$addToSet: {" emails ":" [email protected] "}})
Combining "$addToSet" and "$each" allows you to add several different values, which are not possible with the combination of "$ne" and "$push". For example: To add more than one email address at a time, you can use these modifiers:
> db.users.update ({"_id": ObjectId ("4b2d75476cc613d5ee930164")},
{"$addToSet":
"Emails": {"$each": ["[Email protected]", "[email protected]", "[Email protected]"}})
The $pop modifier can delete an element from either end of the array. {$pop: {key:1}} removes an element from the end of the array, {$pop: {key:-1}} is removed from the head.
$pull can delete an element based on a specific condition, not just a position. For example, there is a list of things to complete, with some problems in order:
> Db.list.insert ({"Todo": ["Dishes", "laundry", "Dry Cleaning"]})
If you want to put the laundry (alundry) in the first place, you can delete it from the list first:
> db.list.update ({}, {"$pull": {"todo": "Laundry"}})
The "$pull" will erase all matching parts. The array [1, 1, 2, 1] executes pull 1, and the result is that there is only one element of the arrays [2].
Positioning modifiers for ④ arrays
If the array has multiple values, and we want to manipulate only a subset of them, this requires some skill. There are two ways to manipulate the values in an array: by location or by positioning operator ("$").
Arrays are all beginning with 0, and you can select elements directly as keys in the following table. For example, here is a document that contains an array of inline documents, such as a blog post with comments.
> Db.blog.posts.findOne ()
{
"_id": ObjectId ("4b329a216cc613d5ee930192")
"Content": "..."
"Comments": [
{
"Comment": "Good post"
"Author": "John"
"Votes": 0
},
{
"Comment": "I thought it is too short"
"Author": "Claire"
"Votes": 3
}
{
"Comment": "Free Watches"
"Author": "Alice"
"Votes":-1
}
]
}
If you want to increase the number of votes in the first comment, you can do this:
> db.blog.update ({"POST": post_id}, {"$inc": {"comments.0.votes": 1}})
However, in many cases, it is not possible to know that you want to modify the subscript of an array without querying the document beforehand. To overcome this difficulty, MongoDB provides the positioning operator "$", which is used to locate and update the element that the query document already matches. For example, if the user John changed his name to Jim, he could replace the name in the comment with a locator:
> db.blog.update ({"Comments.author": "John"}, {"$set": {"Comments.$.author": "Jim"}})
A locator only updates the first matching element.
⑤ modifier speed
If the modification involves spatial allocation slowing down the modification operation, the colleague Su-zhe array becomes longer, MongoDB takes longer to traverse the entire array, and the modifications to each array are slowed down.
The following Python program inserts a key and increments its value 100,000 times (does not involve spatial allocation):
fromPymongoImportConnectionImportTimedb=Connection (). Performance_testdb.drop_collection ("Updates") Collection=Db.upddatescollection.insert ({"x": 1})#Make sure the insert was complete before we start timing collection.find_one ()Start=time.time () forIinchRange (100000): Collection.update ({}: {"$inc": {"x": 1}}) #Make sure the updates is complete before we stop timingCollection.find_one ()PrintTime.time ()-Start
It ran for 7.33 seconds altogether. Wonderful there are more than 13,000 updates.
If it is push 100,000 times:
for in range (100000): collection.update ({}, {'$push' : {') x' : 1}})
The program took 67.58 seconds and was updated less than 1500 times per second.
"Upsert"
Upsert is a special kind of update. If no document meets the update criteria, a new document is created based on this condition and the updated document. If a matching document is found, the update is normal. The Upsert is very handy and does not have to be provisioned, and the same set of code can create and update documents.
Review previous examples of how many page visits were recorded. If there is no upsert, you have to try to query the URL, not found to create a new document, find the words to increase the number of visits. If you put this shoe city JavaScript program (rather than a series of shell commands running with MONGO Scriptname.js), it would look like this:
Check if we have a entry for this page
Blog = db.analytics.findOne ({url: "/blog"})
If we do, add one to the number of views and save
if (blog) {
blog.pageviews++;
Db.analytics.save (blog);
}
Otherwise, create a new document for this page
else {
Db.analytics.save ({url: "/blog", pageviews:1})
}
This means that if someone visits a page, we have to go to the database and then select Update or INSERT. If multiple processes are running this code at the same time, you also have to consider the limitations of documents that cannot be traced to a given URL.
The key uses Upsert, which avoids race problems and reduces the amount of code (the 3rd parameter to update indicates that this is a upsert):
> db.analystics.update ({"url": "/blog"}, {"$inc": {"visits": 1}}, True)
This line of code works exactly like the previous code, but it is more efficient and atomic.
Creating a new document will base the conditional document on it, and then apply the modifier document to it. For example, if you execute a matching key and increase the upsert operation of the corresponding key value, the match is incremented based on:
> Db.math.remove ()
> db.math.update ({"Count": +}, {"$inc": {"Count": 3}}, True)
> Db.math.findOne ()
{
"_id": ObjectId ("4b3295f26cc613d5ee93018f"),
"Count": 28
}
First remove clears the collection, and there is no document in it. Upsert creates a document with a value of 25 for the key "count", then adds 3 to the value, and finally gets the document "Count" 28. If the Upsert option is not turned on, {"Count": 25} does not match to any document, and there is no change.
If you run this upsert (condition {count:25}) again, a new document is created. This is because there is no document match condition (the value of the unique document "Count" is 28).
Save Shell Helper
Save is a shell function that can be inserted when the document does not exist and is updated when it is present. He has only one parameter: document. If this document contains the "_id" key, save will call Upsert. Otherwise, the insert is called. Programmers can easily use this function to quickly modify documents in the shell.
> var x = Db.foo.findOne ()
> x.num = 42
> Db.foo.save (x)
If not save, the last line can be written as follows, but very verbose:
> db.foo.update ({"_id": x._id}, X)
Update multiple documents
By default, an update can only perform actions on the first document that meets the criteria. If more than one document meets the criteria, the remaining documents will not change. To make all matching documents updated, you can set the 4th parameter of update to TRUE.
The multiple file update is useful for schema migrations and can also be used when new features are released for specific users. For example, suppose you want to give a gift to all users who have birthdays on a particular date, you can use multi-document updates to add "gift" to their account.
> db.users.update ({birthday: "10/13/1978"}, {$set: {gift: "Happy birthday!"}}, False, True)
This adds the "gift" key to all user documents that have a birthday of October 1978 113 days.
To know how many documents are updated in the multi-document update, run the GetLastError command. The value of the key "n" is the number you want.
> db.count.update ({x:1}, {$inc: {x:1}}, False, True)
> Db.runcommand ({getlasterror:1})
{
"Err": null,
"Updatedexisting": true,
"N": 5,
"OK": true
}
Here "n" is 5, indicating that 5 documents have been updated. "Updatedexisting" is true to indicate that an existing document has been updated.
Returns the updated document: Findandmodify command.
Example: Suppose we have a collection that includes a process that runs in a certain order. Each of these processes is represented as a document with the following form:
{
"_id": ObjectId (),
"Status": Stat,
"Priority": N
}
"Status" is a string that can be "ready", "RUNNING", or "done". To find the highest priority task with the status "Ready", run the Process function and update its status to "done". Prioritize the processes that are already ready, and then update the status of the highest-priority processes to "RUNNING". When you are finished, change the status to "done".
Programs that use "findandmodify":
> PS = Db.runcommand ({"findandmodify": "Processes",
"Query": {"status": "Ready"},
"Sort": {"Priority":-1},
"Update": {"$set": {"status": "RUNNING"}}). value
> do_something (PS)
> db.process.update ({"_id": ps._id}, {"$set": {"status": "Done"}})
Findandmodify has both the "Update" key and the "remove" key. The "remove" key means that the matching document is deleted from the collection. For example, instead of updating the status now, delete it directly, as follows:
> PS = Db.runcommand ({"findandmodify": "Processes",
"Query": {"status": "Ready"},
"Sort": {"Priority":-1},
"Remove": true}). value
> do_something (PS)
The value corresponding to each key in the Findandmodify command is shown below.
· Findandmodify
String, collection name
· Query
Querying documents, criteria for retrieving documents
· Sort
Criteria for sorting results
· Update
A modifier document that performs an update on the found document.
· Remove
A Boolean type that indicates whether to delete the document.
· New
A Boolean type that indicates whether the document returned before or after the update. The default is the pre-update document.
MongoDB Learning Note II: Create, update, and delete documents