Original: Https://serholiu.com/python-mongodb
these days are learning 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, the use of Python operation MongoDB needs to install Pymongo, 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.
1 from import # Import Module 2 >>> con = Connection ()3 # Connect test database 4 # connect the Post collection in test, equivalent to the 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 >>>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":d Atetime.datetime.now ()}8 9 >>> post2 = {"title":"Python and MongoDB",10"Slug":"Python-mongodb",11"author":"Serho",12"content":"Python and MongoDB ....",13"Tags":["Python","MongoDB"],14" Time":d Atetime.datetime.now ()}>>> Post3 = {"title":"Serho Blog",17"Slug":"Serho-blog",18"author":"Akio",19"content":"Serho Blog is OK ....",20"Tags":["Serho","Blog"],21st" Time":d Atetime.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:
1 >>> posts = Posts.find ()2 >>> count = posts.count ()3 for in posts:4 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 >>> post = Posts.find_one ({"Slug":"Python-mongodb"}) 2 >>> post["author"] 3 U'Serho'4 >>> post["author"] ="HaHa Lu"5 >>> post["title"] ="Test Update"6 >>> post["title"] ="Test Update"7 >>> post["_id"] 8 ObjectId ('4ea0207dd483050fe8000001') 9 >>> posts.update ({"_id":p ost["_id"]},post)>>> post = Posts.find_one ({"_id":p ost["_id"]})>>>PrintPost{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 (2011, 10, 20, 21, 21, 52, 818000),+-U'_id': ObjectId ('4ea0207dd483050fe8000001'),+ U'Slug': 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":p ost["_id"]},{ "$set":2 {"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":p ost["_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":p ost["_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 :p ost[" ]},{" : 2 { Span style= "color: #800000;" > " 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":p ost["_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.
MongoDB python client Pymongo (RPM)