MongoDB (ii) Create an update to delete a document

Source: Internet
Author: User
Tags array length bulk insert modifier

Insert and save document actions

Inserts a document into the target collection with insert, which is added automatically if there is no _id key. finally automatically saved.

>db.foo.insert ({"Bar": "Baz"})

If you want to BULK insert What to do, look at the following code:

>db.foo.insert ([{"_id": 0},{"_id": 1}, "{" _id ": 2}])

There used to be a batchinsert function, and now it's gone. Note that if one of the document inserts fails during bulk INSERT, the document and his subsequent documents will be inserted unsuccessfully. If you want to ignore the error and continue execution, write this:

Db.foo.insert ([{"_id": 3},{"_id": 4},{"_id": 3},{"_id": 5}],continueonerror=true)

MongoDB only makes simple checks when inserting data: Check the basic structure of the document and automatically add one if there is no _id. Check the size, all the documents are <16MB (the designer thinks the set, may also change later). If you want to see the Bson size of a document, you can do this:

Object.bsonsize ({"X": 1})

This allows you to get the Bson size of the document. Don't know what is bson please see what this bson is

Because MongoDB only makes the most basic checks, it is easy to insert illegal data. Then we should only allow trusted source-linked servers in this process.

Delete a document

Delete all documents command:

Db.foo.remove ({})

To delete a document that meets certain criteria:

Db.foo.remove ({title: "blog"})

This will delete the document that satisfies Title=blog, and we can delete only one document that satisfies the criteria:

Db.foo.remove ({title: "blog"},1)

This command deletes the first document that satisfies the criteria.

When we delete all the documents, it will be quicker to delete the collection directly with drop (), but the drop can only be deleted, and the condition deletion cannot be specified!

Update document

Update the document with update, the update has two parameters, one is the query document, to locate the target document needs to be updated, and the other is a modifier, Used to describe what modifications are made to the document that is found. The update operation is inseparable, if two update operations occur simultaneously, then the first server to execute first, and then execute the other.

1. Replace the document

Suppose our previous document was {"_id": 0, "name": "Faner", "Friends": 2}, now we want to move friends and enemises two fields to the subdocument relationship, The simplest way is to replace our previous document with a new document. So we should do it.

var faner = Db.tester.findOne ({name: "Faner"= {"Friends": Faner.friends, "enemies": Faner.enemies}; Delete faner.friends; Delete faner.enemies;db.tester.update ({name:"Faner"},faner};

So we have finished our replacement. But note that if the query condition matches multiple documents, the database runs out of error because the second argument causes all _id to be the same, and no documents are updated. So it's best to specify unique documents with unique key values when updating!
For example _id, and use _id query faster than other fields, this is because of the index relationship, we do not talk about.

2. Using modifiers

If only a part of the document to be updated, then we can use atomicity (do not understand their own Baidu bar. After all, this is a basic skill ~) Update modifier that specifies that some fields of the document are updated.

Db.tester.update ({name: "Faner"},{$set: {x:22}})

We find Name=faner's document and turn his X into 22, which uses our set modifier. $set modifier is used to modify the value of a field, and if the field does not exist, it is created, and we can change the type of the key in addition to modifying the value, as follows:

Db.tester.update ({name: "Faner"},{$set: {x:[1,2,3,4]}})

So we turn our X into an array, we can also become embedded documents and other types, specifically please try it yourself.

If we want to delete a key, we can also use $unset to complete our idea:

Db.tester.update ({name: "Faner"},{$unset: {x:1}})

Note that the value behind this field x is meaningless, anything can be, I am accustomed to write 1, everyone according to their own habits to write their own code.

In addition to our $set and $unset, we also have the $inc modifier (self-increment), $push modifier (Adding an element to the end of an existing array), and so on.

Let's look at the function of each modifier by code:

Db.tester.update ({name: "Faner"},{$inc: {x:1}})//Inc modifier from
//$push modifier is used to add an element to the back of an arrayDb.tester.update ({name: "Faner"},{$push: {x:5}})//push and each combine to add a set of elementsDb.tester.update ({name: "Faner"},{$push: {x:{$each: [6,7,8]}})
//If you want the number of arrays to be fixed, use slice here to assume that the array length is fixed to 10, and that the last added 10 elements are preserved here .
Db.tester.update ({name: "Faner"},{$push: {x:{$each: [6,7,8], $slice:-10}})
//If I want to keep 10 values according to the size of a field, we'll use our $sort here .
//Keep 10 in descending order of field X
Db.tester.update ({name: "Faner"},{$push: {x:{$each: [6,7,8], $slice: -10, $sort: {"x":-1}}})
//If we don't want the numbers in the array to be duplicated, use $addtoset Addtoset can also be used with each
Db.tester.update ({name: "Faner"},{$addToSet: {x:2}})
//delete elements in an array with $pop and $pull (delete multiple elements)
Db.tester.update ({name: "Faner"},{$pop: {x:1}})//Remove an element from the tail
Db.tester.update ({name: "Faner"},{$pop: {x:-1}})//Remove an element from the head
//For manipulating part of an array using the locator operator

Upsert is a special update that if you don't find a document that meets the update criteria, he creates a new document on his own and updates the document as expected. The way to use Upsert is to write the third parameter of the update as true, and the default is False.

And $setoninsert, it will only be set on the first modification, and later updates will not change. The Sava function can be quickly modified, such as Db.tester.save (x) Sava is a shell function that calls Upsert if the document contains a _id key, or insert is called.

Update Multiple documents

By default, updates are only updated for the first document that meets the matching criteria. If you want to update all matching documents, set the fourth parameter of update to TRUE. To know how many documents are updated with the command: Db.runcommand ({getlasterror:1}) (returns information about the last operation, N is the number of documents being updated)

Returns the document that was updated

Use findandmodify command to get updated document, findandmodify definition and function Official document

If you look at the official instructions, I will not be wordy.

MongoDB (ii) Create an update to delete a document

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.