MongoDB Create, update, and delete documents

Source: Internet
Author: User
Tags bulk insert modifier modifiers

1.1 Inserting and saving a document

Inserting is the basic method of adding data to MongoDB. Using the Insert method on the target machine, insert a document:

> Db.foo.insert ({"bar""baz"})

This will add a "_id" key to the document (if it is not) and then save it to MongoDB.

1.1.1 BULK Insert

If you are inserting multiple documents, using BULK INSERT is faster. Bulk INSERT can pass a document-formed array to the database. This approach is useful only if you are inserting multiple documents into a collection, and you cannot bulk insert operations on multiple collections at once. If you are importing raw data (such as importing from a data feed or MySQL), you can use command-line tools such as Mongoimport instead of bulk INSERT, which limits the length of the message when you bulk insert it.

1.1.2 Insertion: Principle and function

When an insert is performed, the driver used converts the data into a Bson form and then sends it to the human database. Database parsing Bson, verify that the "_id" key is included and that the document does not exceed 4MB, other data validation is done, simply save the document as it is in the database. There are good, bad, and most obvious side effects of allowing invalid data insertions, and the advantage is that it makes the database more secure and away from injection attacks. Because the code is not executed at the time of insertion, there is no possibility of this block without an injection attack. Traditional injection attacks are not valid for MongoDB.

1.2 Deleting a document

To delete data from an existing database:

> Db.users.remove ()

The preceding command deletes all 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 a parameter. Given this parameter, only documents that meet the criteria are deleted. For example, to delete all "OptOut" in the Mailing.list collection as true:

> Db.mailing.list.remove ({optout:true})

Delete Data is permanent, cannot be undone, and cannot be deleted.

Deleting a document is usually quick, but clearing the entire collection, deleting the collection directly (and then rebuilding the index) is faster.

1.3 Updating Documents

Use the Update method to modify the document. The update has two parameters, one for querying the document, for finding the document to be updated, and the other is the modifier (modifier) document, which describes what changes are made to the found document.

Updates are atomic: If two updates occur at the same time, the server first executes first, and then another is executed, so that conflicting updates can be delivered in a flash, without interfering with each other: The final update will win.

1.3.1 Document Replacement

Turn it down like this:

You can replace the document with update:

A common mistake is that the query condition matches multiple documents, and then the update results in a duplicate "_id" value due to the presence of the second parameter. The database will make an error without making any changes. (except the shell, the general program will not error, unless using GetLastError)

To avoid this, it is a good idea to ensure that updates always specify unique documents, such as matching by keys such as "_id".

1.3.2 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 efficient. The update modifier is a special key that specifies complex update operations, such as resizing, adding or removing keys, or manipulating arrays or inline documents.

For example, to record website access, when someone accesses, you need to increase the counter, you can use the update modifier atomically to complete this increase:

In PHP, $ represents a variable prefix, and a string that begins with $ in double quotation marks is replaced with a variable, and you can escape $: "\ $foo". You can also use the single quotation mark ' $foo ' to not interpret the variable. You can also set the Mongo.cmd_char of the php.ini file, which can be used with =,:, or any character you think can replace $. If you choose ~, you can use ~inc as \ $inc.

When you use the modifier, the value of "_id" cannot be changed. (Note that "_id" can be changed when the entire document is replaced.) Other key values, including keys for other unique indexes, can be changed.

1. "$set" modifier

"$set" is used to specify a value for a key. If the key does not exist, it is created. This is convenient for update mode or for adding user-defined keys.

The above documents want to add favorite books in, you can use the "$set":

If the user feels like it is another book, "$set" can help:

"$set" modifies the data type, as the user likes is a bunch of books, you can change the value of the "favorite" key into an array

If the user suddenly found that they do not love reading, you can use the "$unset" to remove the key completely:

You can also modify the inline document with "$set":

2. Increase and decrease

The "$inc" modifier to increase the value of an existing key, or to create a key when the key does not exist . This can be very handy for analyzing data, causality, voting, or other numerical changes.

If the game set, if the ball hit the brick, to add points to the player, here the base to 50, you can use the "$inc" modifier to add 50 points to the player:

The fractional key (score) does not exist, so the "$inc" creates the key and sets the value to increment: 50.

The use of "$inc" and "$set" is similar in that it is designed to increase (and decrease) numbers. "$inc" can only be used for integers, long integers, or double-precision floating-point numbers. Using other types of data will cause the operation to fail, including many languages that are automatically converted to numeric types, such as NULL, a Boolean type, or a string that consists of numbers.

The value of the $inc key must be a number. You cannot use strings, arrays, or other non-numeric values. Otherwise, the following error is indicated:

3. Array modifiers

Array operations, which can only be used on keys whose values are arrays. If you cannot push an integer, you cannot make a pop to the string. Use "$set" or "$inc" to modify the scalar value.

If the specified key already exists, "$push" adds an element to the end of the existing array and creates a new array if it does not.

To add a comment, you can use "$push":

This is often the case where a value is not added in the array. You can do this in a query document using "$ne", such as: If the author does not add it in the citation:

You can also use the "$addToSet" to accomplish the same thing, to know that some situations "$ne" simply does not work, sometimes more appropriate to use the "$addToSet."

Combining "$addToSet" and "$each" allows you to add several different values, which are not possible with the combination of "$ne" and "$push".

There are several ways to delete elements from an array, and if you think of the array as a queue and a stack, you can use "$pop", which removes the 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.

Sometimes it takes a certain condition to delete an element, not just the location, "$pull" can do. As follows:

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 [2].

4. Positioning modifier for arrays

MongoDB Create, update, and delete documents

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.