[关闭]
@zhengyuhong 2016-09-14T01:50:16.000000Z 字数 5352 阅读 1757

Python linux mongodb posts

pymongo

1、MongoDB概念

  在MongoDB中,多个文档组成集合,集合与文档也可以组成集合,多个集合也可以组成集合,多个集合组成数据库。一个MongoDB Server可以承载多个独立的数据库,每一个数据库可以拥有一个或者多个集合。每一个数据库都有独立的权限。对比关系数据库,则是,多个行组成一个表,多个表组成一个数据库,SQL Server可以承载多个数据库。

2、Making a Connection with MongoClient

  由于MongoDB Server是服务端,所以必须创建一个客户端去连接服务器进行数据操作。
  在启动MongoDB Server指定了监听端口,默认为27017,在网络中Server也拥有一个IP地址,所以Client用IP地址 + 端口可以连接到Server。

  1. #The first step when working with PyMongo is to create a MongoClient to the running mongod instance. Doing so is easy:
  2. from pymongo import MongoClient
  3. client = MongoClient()
  4. #We can also specify the host and port explicitly, as follows:
  5. client = MongoClient(IP, port)
  6. client = MongoClient('localhost', 27017)

3、Getting a Database  

  A single instance of MongoDB can support multiple independent databases. When working with PyMongo you access databases using attribute style access on MongoClient instances:

  1. db = client.test_database
  2. db = client['test-database']#If your database name is such that using attribute style access wont work (like test-database), you can use dictionary style access instead:
  3. client.database_names()#Get a list of the names of all databases on the connected server.

4、Getting a Collection

  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:

  1. collection = db.test_collection
  2. collection = db['test-collection']#or (using dictionary style access):

  list collections in current database

  1. db.collection_names(include_system_collections=False)

5、Inserting Documents into collection、

5.1、insert_one(document)

  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:

  1. post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]
  2. posts = db.posts # or posts = db['[posts']
  3. ret = posts.insert_one(post)
  4. post_id = ret.inserted_id
  5. print post_id

5.2、insert_many(documents)

  1. ret = posts.insert_many(post_list)# post_list = [psot1,post2,...,postn]

6、Getting documents

6.1、find_one()

  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.

  1. #Here we use find_one() to get the first document from the posts collection:
  2. 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:

  1. ret = posts.find_one({"author": "Mike"})

  We can also find a post by its _id, which in our example is an ObjectId:

  1. posts.find_one({"_id": post_id})
  2. post_id_as_str = str(post_id)
  3. posts.find_one({"_id": post_id_as_str}) # No result
  4. from bson.objectid import ObjectId
  5. posts.find_one({"_id": bson.ObjectId(post_id_as_str)}) # it works

   Iterate over all documents in current collection  

  1. for post in posts.find_one():
  2. print post

6.2、find()

  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”:

  1. for post in posts.find({"author": "Mike"}):
  2. print post

7、count

  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:

  1. posts.count()
  2. posts.find({"author": "Mike"}).count() #match a specific query:

8、update

8.1、replace_one()

  1. 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.

  1. posts.insert_one({"author""Mike""school":"CMU"})
  2. ret = posts.replace_one({"authort":"Mike"},{"author":"Mike","school":"Harvard"})
  3. print result.matched_count # 1
  4. #replace the first document match filter
  5. ret = db.test.replace_one({'x': 1}, {'x': 1}, True)
  6. print ret.matched_count # 0

8.2、update_one()

  1. update_one(filter, update, upsert=False)
  1. users = db.users
  2. John = {"name":"John","age":18,"nickname":["A","B","C"]}
  3. Jim = {"name":"Jim","age":19,"nickname":["D","E","F"]}
  4. users.insert_many([John,Jim])
  5. filter = {"name":"John"}
  6. update = {"$set":{"age":29}}#重置age
  7. update = {"$unset":{"nickname":None}}#删除nickname documentnickname属性)
  8. update = {"$inc":{"age":1}}#age 增加1
  9. update = {"$inc":{"age":11}}#age 减少1
  10. update = {"$push":{"nickname":"H"}}#document list增加单个元素
  11. update = {"$pushall":{"nickname":"H"}}#document list增加多个元素
  12. update = {"$pop":{"nickname":1}}#从数组尾部弹出元素
  13. update = {"$pop":{"nickname":11}}#从数组头部弹出元素
  14. update = {"$pull":{"nickname":"A"}}#从数组中符合特定条件的单个元素
  15. update = {"$pull":{"nickname":["B","C"]}}#从数组中符合特定条件的多个元素
  16. update = {"$addToSet":{"email":"yyy@email.com"}} #如果新加的值不在原列表当中,则加入,就是把原来列表当做一个集合,把新元素添加到集合当中。或者如下借助于$ne定制过滤器然后update
  17. filter = {"name":"John","email":{"$ne":yy@mail.com}}
  18. update = {"$push":{"email":"xxx@mail.com"}}
  19. update = {"$addToSet":{"email":{"$each":["zzz@mail.com","kkk@mail.edu"]}}}# $each 实现了迭代
  20. users.update_one(filter,update)

关于更多更新修改器可以参考官网的Update Operators
Update a single document matching the filter

8.3、update_many()

  1. update_many(filter, update, upsert=False)

Update one or more documents that match the filter.
update需要用到更新修改器,关于修改器参考学习MongoDB--(3-2):利用修改器更新文档

Deleting documents

9.1、delete_one()

  1. delete_one(filter)

Delete a single document matching the filter.定义好filter即可,每一次删除一个

9.2、delete_many()

  1. delete_many(filter)

  Delete one or more documents matching the filter.定义好filter即可,一次性删除符合filter的documents

10、Closing a Connection with MongoClient

  1. client.close()

11、更多参考

pymongo tutorial
Operators
Query and Projection Operators
Aggregation Pipeline Operators
Query Modifiers
Update Operators

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注