How to modify an array of MongoDB fields without modifying the entire field

Source: Internet
Author: User
Tags modifier modifiers

The good point is that the database does not need to be established, after the connection, if the insertion of data operations, the system can create its own, we assume a post collection, which is a number of blog posts composed of documents. Let's insert a few articles to do the experiment.

1>>>ImportDatetime2>>>Post1={"Title":"I Love Python",3"Slug":"I-love-python",4"Author":"Serho",5"Content":"I Love Python ...",6"Tags":["Love","Python"],7"Time":Datetime.Datetime.Now()}89>>>Post2={"Title":"Python and MongoDB",10"Slug":"Python-mongodb",11"Author":"Serho",12"Content":"Python and MongoDB ....",13"Tags":["Python","MongoDB"],14"Time":Datetime.Datetime.Now()}1516>>>Post3={"Title":"Serho Blog",17"Slug":"Serho-blog",18"Author":"Akio",19"Content":"Serho Blog is OK ....",20"Tags":["Serho","Blog"21  "time" :datetimedatetime. Now ()} 22 23 >>> posts. Insert (post1) 24 >> > posts. Insert (post2) 25 >> > posts. Insert (post3)         

When inserting a document, MongoDB automatically adds a "_id" key to each document, which is computed by complexity and is not duplicated, similar to the following:

1     ObjectId(' 4ea0207dd483050fe8000001 ')   

Adding data is such a simple, no need to define the document in advance of the organization, the structure of each document can be different, the above examples I cite is the same, which can be set according to the actual needs, I this is to explain the following. After inserting, it must be the first query, the following query out all the documents in the Post collection:

1     posts.  Findposts.  Countpostspost       

The database uses cursors to return the results of find, and there are several methods on the cursor, such as count () above, to get the total number of documents queried. This example will return "Count=3″ and the three documents above." More query methods are explained later, and these methods are more powerful.

After insertion, you may find that you need to modify it, so here are some ways to modify it. If the need for drastic changes, what is a substantial change, such as the Post1 Title,slug,author and so on have been modified, my understanding is greater than a key modification is called large-scale modification. Modify a thing, you have to find him first, so the query method is very important, unfortunately, this preparation will be later. Let's change it by looking for one.

1>>>Post=Posts.Find_one({"Slug":"Python-mongodb"})2>>>Post["Author"]3U ' Serho '4>>>Post["Author"]="HaHa Lu"5>>>Post["Title"]="Test Update"6>>>Post["Title"]="Test Update"7>>>Post["_ID"]8ObjectId(' 4ea0207dd483050fe8000001 ')9>>>Posts.Update({"_ID":Post["_ID"]},Post)10>>>Post=Posts.Find_one({"_ID":Post["_ID"]})11>>>PrintPost12{U ' author ':U ' HaHa Lu ',U ' title ':U ' Test Update ',13U ' tags ':[U ' Python ',U ' MongoDB '],14U ' content ':u ' Python and MongoDB ... '  15 u ' time ' : datetime. Datetime (201110202121 Span class= "Mi" >5281800016 u ' _id ' : objectid ( " 4ea0207dd483050fe8000001 ' ), 17 u ' slug ' : Span class= "s" >u ' Python-mongodb ' }          

First we get an article according to Slug, and then we can get the value of the key through the Python dictionary access method, then reset it, then update the Post collection, when updating the whole collection, you have to match the document to be changed, using _id this property to update is the more common method, Because you changed the other, this can not be changed. The most common mistake in performing an update is to find more than one document in a restricted condition, and if so, the database does not update the collection, and it is best to use _id to match.

If only one key is updated, then it is not so much trouble, you can use the "$set" modifier, specify a key, if it does not exist, you can create. For example, I want to continue to update the content of the above article, you can do this (remember, to modify it, you must first find it, here I use the above query to find the _id value):

1     posts.  Update({"_id":post["_id"]},{"$set"{"content":"Test Update SET ....})               

MongoDB modification is very powerful, you can change the data type, such as the tags of the array into a normal string. If you want to delete this key after "$set", you can use "$unset". If there is a key in my post that is views, that is, the number of times the article is accessed, I would like to add 1 to the value after each access to this article, what should I do? So the "$inc" modifier appeared, which can be used to increase the value of the existing key, if not, then create it, similar to the use of:

1     2     posts.  Update({"_id":post["_id"]},{"$inc"{"views":1}}) 

What if I want to modify the contents of tags in this array? One way is to use $set as a whole to modify, but just change some of the elements inside, MongoDB ready for the array of modifiers. For example, if you want to add a "Test" to tags, you need to use "$push", which adds an element to the end of the array:

1     posts.  Update({"_id":post["_id"]},{"$push": {"tags":"Test" }})

To avoid adding duplicates, you can change the "$push" to use "$addToSet", and if you need to add multiple values, you can use it with "$each" so that you can add non-duplicates, as follows:

1   2     posts.  Update({"_id":post["_id"]},{"$addToSet"{"tags": {"$ Each ": [" Python "," Each "]         }}) 

After the addition, the following is deleted, you can think of arrays as stacks and queues, using "$pop" to operate, such as the above:

1     posts.  Update({"_id":post["_id"]},{"$pop": {"tags":1}}) 

This will remove tags inside the last one, change to 1 then delete the first one. You can use "$pull" to delete the value specified in the array, which deletes all matching values in the array. How do I change one of these values? Can be deleted first, and then add a go in, there is a direct location modification. For example tags array, "Python" is the first, want to change it to "Python", can be directly selected by subscript, that is tags[0], and then use the above "$set" and other modifiers, if not sure you can use $ to locate:

1     posts.  Update({"tags":"MongoDB"},{"$set": {"tags.$":"Hello"}}) 

This will first search tags to meet the "MongoDB", if found, modify it to "Hello". Can see the above update this function has two parameters, it also has a 3rd parameter Upsert, if set to "True", if no matching document is found, the match will be based on a new document, the actual instance will not speak.

Now using Python to insert, the modification data has been finished, and will continue to explain the powerful query function and aggregation function. Wait for the next article.

How to modify an array of MongoDB fields without modifying the entire field

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.