MongoDB Learning Notes-Create, update, delete documents

Source: Internet
Author: User
Tags bulk insert modifier

Create

In MongoDB, you use the Insert method to insert a document into a collection and then save it to MongoDB.

Db.foo.insert ({"hehe": "hehe"})

If you want to bulk INSERT, you can use the following form: Db.foo.insert ([{"Hehe": "hehe"},{"haha": "haha"}])

    • Insert Check

MongoDB only makes the most basic checks on data when inserting data-examining the basic structure of the document. If there is no "_id" field, it will be automatically added, and all documents must be less than 16MB (this value is artificially defined by the MongoDB designer and may increase in the future). This limitation is primarily designed to prevent undesirable pattern designs and to ensure consistent performance.

Because MongoDB only makes the most basic checks, it is easy to insert illegal data. Therefore, only trusted sources should be allowed to connect to the database.

Delete

You can use Remove () and drop () to delete data in MongoDB. Delete Data is permanent, cannot be undone, and cannot be recovered.

Remove () is used to delete a document with two overloads, as follows:

Db.foo.remove (): Deletes all documents in the entire Foo collection. But Foo will not be deleted, nor will Foo's metadata be deleted

Db.foo.remove (search condition): Delete a document for a specified condition

Drop () is used to empty the entire collection, and it quickly deletes the document. As follows:

Db.foo.drop ()

Update

The Update method is used for updating documents in the database. It has two parameters, one for querying the document, for locating the target document that needs updating, and the other is the modifier (modifier) document. Used to describe what modifications are made to the found document. It is best to use "_id" to match query document parameters. This prevents the query criteria from matching to multiple documents.

->var A=db.foo.findone ({"hehe": "hehe"}); ->delete a.hehe->a.wuli= "Wuli Tao Tao"; ->db.foo.update ({"hehe": "hehe"},a);

    • Partial update (modifier)

Part of the update to the document is done by updating the modifier (update modifier). The update modifier is a special key used to specify complex update operations, such as modifying, adding, or deleting keys, and manipulating arrays and inline documents

$set: Used to specify a value for a field. If this field does not exist, it is created.

Db.foo.update ({"_id": "123"},{"$set": {"NB": "New Baby"}});

if the "NB" field does not exist, a "NB" field is created and the "NB" field value is updated instead. The $set can even modify the type of the key. as follows:

Db.foo.update ({"_id": "123"},{"$set": {"NB": ["New Bady", "Niubi"]}});

"$set" can also be used for inline documents:

Db.foo.update ({"_id": "123"},{"$set": {"Author.name": "Tanggu Three Less"}})

$unset: Used to delete a field, as follows:

Db.foo.update ({"_id": "123", {"$unset": {"NB": ["New Bady", "Niubi"]});

$inc: A value that is used to add an existing key and creates one if it does not exist. It can only be used for integer, long, or floating-point types. If you use other data types, you will get an error.

Db.foo.update ({"_id": "123"},{"$inc": {"score": 50}})

If the score key does not exist, it is created and the value is set to 50. Each time you call the method above, score will increment by 50.

    • Data modifiers

$push: Adds an element to the end of the array and creates an array if the array does not exist.

Db.foo.update ({"_id": "123"},{"$push": {"Age": 12}})

$each: add more than one value at a time.

Db.foo.update ({"_id": "123"},{"$push": {"times": {"$each": [1,4,3,2,2]}}})

$slice: The maximum length of the qualifier group. Its value must be a negative integer. If you add a value that exceeds the limit, only the last added element will be included. Must be used with "$each".

Db.foo.update ({"_id": "123"},{"$push": {"Top10": {"$each": ["hehe", "haha", "Wowo"], "$slice":-10}})

$sort: Sort the array elements as the name implies. Must be used with "$each".

Db.foo.update ({"_id": "123"},{"$push": {"Top10": {"$each": ["hehe", "haha", "Wowo"], "$slice": -10}, "$sort": {"Times":- 1}})

$ne/$addToSet: Guarantees that elements added to the array are not duplicated.

Db.foo.update ({"_id": "123"},{"$ne", "hehe"},{"$push": {"NB": "Hehe"}})

Db.foo.update ({"_id": "123"},{"$addToSet": {"emails": "[email protected]"}})

the difference between $ne $addToSet: $ne can not be used with $each, as can be seen in the example above. $addToSet can be$addToSet combined $each can add multiple elements at once

Db.foo.update ({"_id": "123"},{"$addToSet": {"$each": ["[Email protected]", "[Email protected]"}})

$pop/$pull: Deletes an array element. $pop to delete the position elements of the tail and the ends of the array. Sometimes you need to delete an element based on a specific condition, rather than just the location of the element, you can use "$pull" to do so. $pull deletes all matching documents.

Db.foo.update ({"_id": "123"},{"$pop": {"title": 1}})

Db.foo.update ({},{"$pull"}:{"_id": "123"})

    • Array positioning modifier

There are two ways to manipulate an array of elements: by subscript or by locating the operator $.

For example, a document has the following format:

{

"_id": "123",

"Comments": [{"comment": "hehe", "Author": "Zs"}]

}

    • Use $ to modify the value of the author key

Db.foo.update ({"_id": "123"},{"$set": {"comments.$.author": "LS"}})

    • Upsert

Upsert is a special kind of update. If a document that meets the update criteria is not found, a new document is created based on the document you want to update. If found, the update is normal. At the same time, Upsert can not only avoid the problem of race state, but also reduce the amount of code. How to use: Set the Update method the third parameter is true.

    • Update multiple documents

By default, an update can only take effect on the first document that meets the criteria. To update multiple qualifying documents, you can set the fourth parameter of the Update method to True.

Write security mechanism

Write Security (write Concern) is a client setting that controls the level of security that is written. There are two most basic write security mechanisms, reply-to-write (acknowledged write), and non-reply-to-write (unacknowledged write). The answer write is the default: The database will tell you if the write operation was executed successfully. Non-responsive writes do not return any corresponding, so it is not possible to know if the write was successful. prior to 2012, MongoDB's default write security mechanism was non-answer write. So when you use MongoDB before 2012, remember to explicitly set the write security mechanism to write -

MongoDB Learning Notes-Create, update, 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.