Python Operation MongoDB Database

Source: Internet
Author: User
Tags install mongodb modifier modifiers

Original address: Https://serholiu.com/python-mongodb

These days in the study of Python web development, so prepare to do a blog to practice practiced hand, of course, just practiced hand, blog has wordpress such a good thing, why still build their own cars? decided to use the Tornado framework, and then the database side decided to familiarize yourself with the non-relational database such as MongoDB. Python makes me feel relaxed and paired with MongoDB, which is really good.

Here are some basic uses of Python operation MongoDB, first introduce MongoDB, this is now a very powerful NoSQL database, there is no relational database that kind of table such concepts, like a dictionary in Python, a key corresponding to a value, Then these key values form a document, and then the document is composed of a collection, the collection is composed of a database, the type is very rich, using Python to manipulate MongoDB needs to install MongoDB Python driver, after the installation is complete, you can start with me.

Start the database (the method is not the focus of this article) and connect to the database.

 1234 
 >>> from pymongo import  Connection  #导入模块 >>> con = connection () >>> db = span class= "n" >con. Test  #连接test数据库 >>> posts = db. Post  #连接test中的post集合, equivalent to table in MySQL          

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 2 3 4 5 6 7 8 910111213141516171819202122232425
>>>ImportDatetime>>>Post1={"Title":"I Love Python","slug": "I-love-python","Author": "Serho","Content": "I love Python ...","Tags": ["Love", "Python"],"Time":d Atetime.datetime.now ()}>>>Post2={"Title":"Python and MongoDB","slug": "python-mongodb","Author": "Serho","Content": "Python and MongoDB ....","Tags": ["Python", "MongoDB"],"Time":d Atetime.datetime.now ()}>>>Post3= { "title" : "Serho Blog" , "slug": "serho-blog",  "author": "Akio", " time ": Datetime.datetime.now ()}>>> posts. Insert (post1) >>>  Posts. Insert (post2) >>>  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:

1234
Posts.  Find()posts.  Count()posts: print post         

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 2 3 4 5 6 7 8 91011121314151617
>>>Post=Posts.Find_one({"Slug":"Python-mongodb"})>>>Post["Author"]U ' Serho '>>>Post["Author"]="HaHa Lu">>>Post["Title"]="Test Update">>>Post["Title"]="Test Update">>>Post["_ID"]ObjectId (' 4ea0207dd483050fe8000001 ')>>>Posts.Update({"_ID":Post[ "_id" ]},post) >>> post = posts.find_one ({:post [ "_id" ]}) >>> print span class= "n" >post{u ' author ': U ' HaHa Lu ', U ' title ': U ' Test Update ',  U ' tags ': [u ' Python ', u ' MongoDB '], u ' content ': U ' Python and MongoDB ... ',  U ' time ': Datetime.datetime (+, A, ten, A, A, 818000),  U ' _id ': ObjectId (' 4ea0207dd483050fe8000001 '), Span class= "Go" > U ' slug ': U ' python-mongodb '}           

First we get an article based on 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, you have to match the document to be changed when updating the whole collection, it is more common to use _id this property to update the method, because You have 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
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
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.

Python Operation MongoDB Database

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.