Create, update, and delete a document in MongoDB

Source: Internet
Author: User
Tags findone

Create document

Insert data into MongoDB using insert,

Example: DB. refactor. insert ({"refactor's blog": "http://www.cnblogs.com/refactor "})

This operation adds a "_ id" Key to the document and stores it in the database.

Batch insert

If you want to insert multiple documents, batch insertion is faster. Batch insertion can input data composed of documents to the database.

Batch insertion is only a single TCP request, avoiding the overhead caused by many fragmented requests. because a large number of message headers are not required,

This reduces the insertion time. Each time a single document is sent to the database, a header will be generated to tell the database to perform operations on the specified set.

Insert operation. If batch insert is used, the database does not need to repeat the header information of each document.

The maximum message length of the current version of MongoDB is 16 Mb. This limit applies when batch inserts are used.

Principles and functions of insert

When insert is executed, the driver will convert the data into bson format, and then send it to the database. The database will be parsed.

Bson: checks whether the "_ id" Key is included and does not exceed 16 Mb. In addition, no verification is performed, but the document is simply as original.

Store data in the database. The disadvantage is that you can insert invalid data, which makes the database safer and avoids injection attacks.

Drivers in all mainstream languages will check the validity of some data before transmitting the data (whether the document is too long, whether it contains non-UTF-8 characters,

Whether the unknown type is used). You can also use the -- objcheck option when starting the database server so that the server will insert

Check the validity of the document structure before, and sacrifice the performance.

View the size (in bytes) of the DOC file converted to bson, and use object. bsonsize (DOC) in shell)

 

Delete document

DB. Users. Remove ()

All documents of the users set will be deleted, but the set itself will not be deleted, and the original indexes will be retained.

The remove function can take a query document as an optional parameter. Given this parameter, only eligible documents will be deleted.

DB. Users. Remove ({"name": "refactor "})

The deleted data is permanent and cannot be undone or restored.

If you want to clear the entire set, directly deleting the Set (and then re-indexing) is faster than deleting all the documents in the set.

Delete collection: DB. drop_collection ("users ")

 

Update document

Update has two parameters: query the document to find the document to be updated, and modify the document to describe the changes to the document to be found.

Update operations are atomic. If two updates occur at the same time, they are first executed on the server, and then executed on the other. The last update is displayed in the database.

Document Replacement

The simplest update method is to use a new document to replace the matching document, which is applicable when the pattern structure is greatly changed. For example

{
"Name": "refactor ",
"Friends": 20,
Enemies: 2
}

Change

{
"Name": "refactor ",
"Relationships ":
{
"Friends": 20,
Enemies: 2
}
}

 

Use Modifier

Generally, a document only has a part of updates. The Atomic "Update modifier" is used to specify complex update operations. For example:

Adjust, add, and delete keys, operate arrays, and operate embedded documents.

Generally, websites have counters to count the number of public users. You can use the atomic modifier to perform the entire function. For example:

 

Getting started with "$ set" Modifier

"$ Set" is used to specify the value of a key. If the key does not exist, it is created, which is convenient for updating mode or adding a user-defined key.

For example:
DB. Users. insert (
{
"Name": "refactor ",
"Age": 23,
"Sex": "male"
}
)
Add favorite books:
DB. Users. Update (
{
"Name": "refactor"
},
{
"$ Set": {"book": "War and Peace "}
}
)
DB. Users. findone (
{"Name": "refactor "}
)
Modify favorite data
DB. Users. Update (
{
"Name": "refactor"
},
{
"$ Set": {"book": "War and peace2 "}
}
)
"$ Set" can modify the Data Type of a key. If you prefer multiple books,
Convert the book key value to an array
DB. Users. Update (
{
"Name": "refactor"
},
{
"$ Set": {"book": ["War and Peace", "War and peace2"]}
}
)
Use "$ Unset" to delete the key. If no key is to be deleted, no error is returned.
DB. Users. Update (
{
"Name": "refactor"
},
{
"$ Unset": {"book": 1}
}
)
Use "$ set" to modify embedded documents
DB. Blog. insert (
{
"Title": "refactor's blog ",
"Content": "refactor's blog test ",
"Author ":
{
"Name": "refactor ",
"Email": "295240648@163.com"
}
}
)

DB. Blog. Update (
{
"Author. Name": "refactor"
},
{
"$ Set": {"author. Name": "refactor2 "}
}
)
DB. Blog. findone (
{
"Title": "refactor's blog"
}
)
When adding, modifying, or deleting a key, you should use the $ modifier. You must use the modifier starting with $ to modify the key-value pair.

 

Increase and decrease with "$ Inc"

"$ Inc" is used to increase the value of an existing key. If no key exists, it is added. It is used to analyze data, cause and effect relationships, vote, or other places with changed values.

For example:

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

Use "$ Inc" to add a key pageviews. The default value is 10000.

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

Use "$ Inc" to give the key pageviews, and add another 10000

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

Use "$ Inc" to give the key pageviews, and then reduce it by 10000

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

"$ Inc" is similar to "$ set" to add or remove numbers. "$ Inc" can only be used for integers, long integers, or double-precision floating points.

Although many languages can convert strings consisting of null, bool, and numbers into numbers, an error still occurs when "$ Inc" is used:

The value of the "$ Inc" Key must also be a number.

 

Array Modifier

"$ Push" and "$ pop" can only be used for arrays.

If the specified key already exists, "$ push" adds an element to the end of the existing array. If the key does not exist, a new array is created.

For example:

DB. Blog. insert (
{
"Title": "refactor's blog ",
"Content": "refactor's blog test ",
"Author ":
{
"Name": "refactor ",
"Email": "295240648@163.com"
}
}
)

Add a "comment" key containing an array to the preceding document and push a comment to the comment array.

This array is automatically created and added to the comments:

DB. Blog. Update (
{"Title": "refactor's blog "},
{
$ Push:
{
"Comments ":
{
"Name": "refactor2 ",
"Content": "nice"
}
}
}
)

You also want to add a comment:

DB. Blog. Update (
{"Title": "refactor's blog "},
{
$ Push:
{
"Comments ":
{
"Name": "refactor3 ",
"Content": "good"
}
}
}
)

If a value is not in the array, add it. You can use "$ ne" When querying the document ".

 

Use "$ addtoset"

DB. Users. insert (
{
"Username": "refactor ",
"Emails ":
[
"295240648@163.com ",
295240648@126.com"
]
}
)

Add a new address to emails and use "$ addtoset" to avoid duplication.

DB. Users. Update (
{"Username": "refactor "},
{
"$ Addtoset ":
{
"Emails": "295240648@163.com"
}
}
)

This way, "295240648@163.com" is not inserted into emails

DB. Users. Update (
{"Username": "refactor "},
{
"$ Addtoset ":
{
"Emails": "295240648@qq.com"
}
}
)

The 295240648@qq.com is inserted into the emails.

 

You can use "$ addtoset" and "$ each" together to add different values.

DB. Users. Update (
{"Username": "refactor "},
{
"$ Addtoset ":
{
"Emails ":
{
"$ Each ":
[
"295240648@111.com ",
"295240648@112.com ",
295240648@113.com"
]
}
}
}
)

 

You can use "$ pop" to delete elements from any end of the array.

{$ POP: {key: 1} deletes an element from the end of the array.
{$ POP: {key:-1} deletes an element from the array header.

You can use "$ pull" to delete elements based on specific conditions or by location.

DB. Users. Update (
{"Username": "refactor "},
{
"$ Pull ":
{
"Emails": "295240648@111.com"
}
}
)

"$ Pull" deletes all matched parts. For the array [,], run pull 1. The resulting array is [2].

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.