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.
1 >>> from Pymongo import Connection #导入模块
2 >>> con = Connection ()
3 >>> db = Con.test #连接test数据库
4 >>> posts = Db.post #连接test中的post集合, equivalent to a 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 >>> Import datetime
2 >>> 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",
"slug": "python-mongodb",
"Author": "Serho",
"Content": "Python and MongoDB ....",
"Tags": ["Python", "MongoDB"],
"Time":d Atetime.datetime.now ()}
15
>>> post3 = {"title": "Serho Blog",
"slug": "serho-blog",
"Author": "Akio",
"Content": "Serho Blog is ok ...",
"Tags": ["Serho", "Blog"],
"Time":d Atetime.datetime.now ()}
22
>>> 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 post 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"]})
One >>> print 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 (2011, 10 , (+, +, 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
2 >>> 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
2 >>> posts.update ({"_id":p ost["_id"]},{"$addToSet":
3 {"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.
SOURCE Link: Http://serholiu.com/python-mongodb
Python even MongoDB