@zhengyuhong
2016-09-14T01:50:16.000000Z
字数 5352
阅读 1757
Python linux mongodb posts
在MongoDB中,多个文档组成集合,集合与文档也可以组成集合,多个集合也可以组成集合,多个集合组成数据库。一个MongoDB Server可以承载多个独立的数据库,每一个数据库可以拥有一个或者多个集合。每一个数据库都有独立的权限。对比关系数据库,则是,多个行组成一个表,多个表组成一个数据库,SQL Server可以承载多个数据库。
由于MongoDB Server是服务端,所以必须创建一个客户端去连接服务器进行数据操作。
在启动MongoDB Server指定了监听端口,默认为27017,在网络中Server也拥有一个IP地址,所以Client用IP地址 + 端口可以连接到Server。
#The first step when working with PyMongo is to create a MongoClient to the running mongod instance. Doing so is easy:from pymongo import MongoClientclient = MongoClient()#We can also specify the host and port explicitly, as follows:client = MongoClient(IP, port)client = MongoClient('localhost', 27017)
A single instance of MongoDB can support multiple independent databases. When working with PyMongo you access databases using attribute style access on MongoClient instances:
db = client.test_databasedb = client['test-database']#If your database name is such that using attribute style access won’t work (like test-database), you can use dictionary style access instead:client.database_names()#Get a list of the names of all databases on the connected server.
A collection is a group of documents stored in MongoDB, and can be thought of as roughly the equivalent of a table in a relational database. Getting a collection in PyMongo works the same as getting a database:
collection = db.test_collectioncollection = db['test-collection']#or (using dictionary style access):
list collections in current database
db.collection_names(include_system_collections=False)
Data in MongoDB is represented (and stored) using JSON-style documents. In PyMongo we use dictionaries to represent documents. As an example, the following dictionary might be used to represent a blog post:
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]posts = db.posts # or posts = db['[posts']ret = posts.insert_one(post)post_id = ret.inserted_idprint post_id
ret = posts.insert_many(post_list)# post_list = [psot1,post2,...,postn]
The most basic type of query that can be performed in MongoDB is find_one(). This method returns a single document matching a query (or None if there are no matches). It is useful when you know there is only one matching document, or are only interested in the first match.
#Here we use find_one() to get the first document from the posts collection:posts.find_one()
find_one() also supports querying on specific elements that the resulting document must match. To limit our results to a document with author “Mike” we do:
ret = posts.find_one({"author": "Mike"})
We can also find a post by its _id, which in our example is an ObjectId:
posts.find_one({"_id": post_id})post_id_as_str = str(post_id)posts.find_one({"_id": post_id_as_str}) # No resultfrom bson.objectid import ObjectIdposts.find_one({"_id": bson.ObjectId(post_id_as_str)}) # it works
Iterate over all documents in current collection
for post in posts.find_one():print post
To get more than a single document as the result of a query we use the find() method. find() returns a Cursor instance, which allows us to iterate over all matching documents.
Just like we did with find_one(), we can pass a document to find() to limit the returned results. Here, we get only those documents whose author is “Mike”:
for post in posts.find({"author": "Mike"}):print post
If we just want to know how many documents match a query we can perform a count() operation instead of a full query. We can get a count of all of the documents in a collection:
posts.count()posts.find({"author": "Mike"}).count() #match a specific query:
replace_one(filter, replacement, upsert=False)
Replace a single document matching the filter. The upsert option can be used to insert a new document if a matching document does not exist.
posts.insert_one({"author":"Mike","school":"CMU"})ret = posts.replace_one({"authort":"Mike"},{"author":"Mike","school":"Harvard"})print result.matched_count # 1#replace the first document match filterret = db.test.replace_one({'x': 1}, {'x': 1}, True)print ret.matched_count # 0
update_one(filter, update, upsert=False)
users = db.usersJohn = {"name":"John","age":18,"nickname":["A","B","C"]}Jim = {"name":"Jim","age":19,"nickname":["D","E","F"]}users.insert_many([John,Jim])filter = {"name":"John"}update = {"$set":{"age":29}}#重置ageupdate = {"$unset":{"nickname":None}}#删除nickname document(nickname属性)update = {"$inc":{"age":1}}#age 增加1update = {"$inc":{"age":11}}#age 减少1update = {"$push":{"nickname":"H"}}#document list增加单个元素update = {"$pushall":{"nickname":"H"}}#document list增加多个元素update = {"$pop":{"nickname":1}}#从数组尾部弹出元素update = {"$pop":{"nickname":11}}#从数组头部弹出元素update = {"$pull":{"nickname":"A"}}#从数组中符合特定条件的单个元素update = {"$pull":{"nickname":["B","C"]}}#从数组中符合特定条件的多个元素update = {"$addToSet":{"email":"yyy@email.com"}} #如果新加的值不在原列表当中,则加入,就是把原来列表当做一个集合,把新元素添加到集合当中。或者如下借助于$ne定制过滤器然后updatefilter = {"name":"John","email":{"$ne":yy@mail.com}}update = {"$push":{"email":"xxx@mail.com"}}update = {"$addToSet":{"email":{"$each":["zzz@mail.com","kkk@mail.edu"]}}}# $each 实现了迭代users.update_one(filter,update)
关于更多更新修改器可以参考官网的Update Operators
Update a single document matching the filter
update_many(filter, update, upsert=False)
Update one or more documents that match the filter.
update需要用到更新修改器,关于修改器参考学习MongoDB--(3-2):利用修改器更新文档
delete_one(filter)
Delete a single document matching the filter.定义好filter即可,每一次删除一个
delete_many(filter)
Delete one or more documents matching the filter.定义好filter即可,一次性删除符合filter的documents
client.close()
pymongo tutorial
Operators
Query and Projection Operators
Aggregation Pipeline Operators
Query Modifiers
Update Operators