Create, update, and delete a document under MongoDB

Source: Internet
Author: User
Tags server resume

1. Positioning modifier of the array

If the array has multiple values, you only want to modify some of them. You can use the position or positioning operator.

For example, change the first value of the previous e-mail array "295240648@163.com" to "295240648@136.com"

DB. Users. Update (
{"Username": "refactor "},
{
"$ Set ":
{
"Emails.0": "295240648@136.com"
}
}
)

In many cases, you do not know how to modify the subscript of the array without pre-query. MongoDB provides the positioning operator "$"

Locate and update the matching elements of the query document.

 

 

2. modifier speed

Some modifiers run fast. "$ Inc" does not need to change the document size. You only need to modify the key value, so the modification speed is very fast.

The array modifier may slow down the document size. "$ set" can be modified immediately when the document size does not change. Otherwise, the performance may also decrease.

MongoDB reserves some blank space for the document to adapt to the size change (in fact, the system will respond accordingly according to the normal size change of the document)

But if it exceeds the original space, it is still necessary to allocate a new space. In addition to slowing down the space allocation,

At the same time, as the array grows, MongoDB takes a longer time to traverse the entire array, and the modification to each array slows down.

 

"$ Push" or other array modifiers are recommended. However, if "$ push" becomes the efficiency bottleneck, you need to separate the embedded array and put it

In a separate set.

 

3. upsert

Upsert is a special update. If no document meets the update condition, a new document is created based on this condition and the updated document.

If a matching document is found, the update is normal. upsert is no better than the preset set. The same set of code can be created and the document can be updated.

You can use the upsert Method for previously created website counters. Create a document if it does not exist and update it if it exists.

DB. Users. insert (
{
"Url": "http://www.cnblogs.com/refactor ",
"Pageviews": 12345
}
)

Use upsert

DB. Users. Update (
{"Url": "http://www.cnblogs.com/refactor "},
{"$ Inc": {"pageviews": 1 }},
True
)

Note that the third parameter of update indicates that upsert is enabled.

Remove from set:

DB. Users. Remove ({"url": "http://www.cnblogs.com/refactor "})

Use upsert

DB. Users. Update (
{"Url": "http://www.cnblogs.com/refactor "},
{"$ Inc": {"pageviews": 1 }},
True
)

 

4. Save Shell

Save is a shell function that can be inserted when the document does not exist and updated when it exists. It only has one parameter: document. If this document has

"_ Id" Key, save Will call upsert, otherwise it will call insert. programmers can easily use this function to modify the document in Shell

We can see that dB. Users. Save (X) and DB. Users. Update ({"_ id": X. _ id}, x) have the same effect.

 

5. Update multiple documents

By default, the update operation can only be performed on the first document that meets the conditions. To update multiple documents that meet the conditions, you can set the update

The fourth parameter is true.

Only the first matching item is updated.

DB. Users. Update (
{"Url": "http://www.cnblogs.com/refactor "},
{& Quot; $ set & quot;: {& quot; pageviews & quot;: 50000 }}
)

Update all matching items

DB. Users. Update (
{"Url": "http://www.cnblogs.com/refactor "},
{"$ Set": {"pageviews": 50000 }},
False,
True
)

Note: The update behavior may be changed in the future (the server may update all matching documents by default, which will be updated only when the fourth parameter is false.

The first document), so it is recommended to indicate whether to update multiple documents each time.

To know how many documents have been updated during multi-document update, run the getlasterror command. The value of the key "N" is the number.

You can use the findandmodify command to obtain the updated document.

 

6. instant completion

The insert, delete, and update operations are completed instantly because they do not need to wait for the database to respond. This is not an asynchronous operation. The client sends the document

After the server is deleted, the client will not receive the response from the server, for example, the server operation fails.

The advantage of this feature is that the speed is fast, and it is only restricted by the client's sending speed or network speed. However, there will also be many problems, and the client may

Non-existent server sending documents, etc.

 

7. Security Operations

If you want to complete an e-commerce system, if someone has ordered something, the application needs time to make sure the order goes smoothly. If an error occurs during execution, you have to re-execute it.

MongoDB uses an insecure version by default, because applications built on relational databases do not care about the Returned Code and do not check the returned code.

Return code, but you have to wait for this return code, which will cause performance degradation.

The safe version runs the getlasterror command immediately after the operation is completed to check whether the execution is successful. The driver will wait for the database to respond, and then

An exception is thrown when errors are properly handled. In this way, developers can use their own language to handle database errors. If the operation succeeds, getlasterror

Additional information will be given as a response (for example, the number of affected documents will be given for updates and deletions)

The cost of security is performance. Even if you ignore the client's overhead for handling exceptions (this overhead is generally heavyweight), wait for the database to respond to the exception by sending only

The message time is an order of magnitude higher, so we need to weigh the importance and speed requirements of the database.

 

8. Capture Common Errors

Security operations are also a good way to debug Database "strange" behaviors. Even if security operations are finally removed from the production environment, a large number

This avoids many common database usage errors. The most common error is duplicate keys.

Duplicate key errors often occur when you try to insert an occupied "_ id" value into the file. MongoDB does not allow multiple documents with the same "_ id" value in a collection,

If a duplicate key error occurs during secure insertion, the security check will find this server error and throw an exception. In unsafe mode, the database does not respond,

Therefore, we do not know that the insertion failed.

 

9. Requests and connections

The database creates a queue for each MongoDB database connection to store the connection request. When the client sends a request, it is placed at the end of the queue.

Only requests in the queue are executed, and subsequent requests are executed.

Note: Each connection has an independent queue. If you open two shells, there will be two database connections. Execute the insert operation in one shell, and then execute the insert operation in the other shell.

Query may not be able to get the inserted document, but in the same shell, it is certainly possible to execute the query after insertion. manual reproduction of this behavior is not easy, but it is busy

Server, staggered insertion/search is very likely. When developers use a thread to insert data and Erie threads to check whether data is inserted successfully, they will often encounter

This problem occurs in one or two seconds. It seems that no data is inserted at all, but then the data comes up again.

 

Pay special attention to this behavior when using the C # driver, because the driver uses the connection pool. To improve efficiency, the driver and the server resume multiple connections.

(A connection pool) and distribute requests to these connections. Fortunately, the driver provides some mechanisms to ensure that a series of requests are processed by one connection.

 

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.