python操作MongoDB(API)

 1 from pymongo import MongoClient
 2 from datetime import datetime
 3 
 4 
 5 class TestMongo(object):
 6 
 7     def __init__(self):
 8         self.client = MongoClient()   # 连接数据库
 9         self.db = self.client['blog']   # 使用blog数据库
10 
11     def add_one(self):
12         """新增数据"""
13         post = {
14             'title': '新的标题',
15             'content': '博客内容。。。。',
16             'created_at': datetime.now(),
17             'view': 10
18         }
19         return self.db.blog.posts.insert_one(post)    # 数据库下的集合(表)名为 blog.posts
20 
21     def get_one(self):
22         """查询一条数据"""
23         return self.db.blog.posts.find_one()
24 
25     def get_more(self):
26         """查询所有数据"""
27         return self.db.blog.posts.find()
28 
29     def get_from_oid(self, oid):
30         """根据记录的ID来获取数据"""
31         from bson.objectid import ObjectId    # 使用ObjectID才能查询到数据
32         return self.db.blog.posts.find_one({'_id': ObjectId(oid)})
33 
34     def update(self):
35         """修改数据"""
36         # 修改一条数据
37         rest = self.db.blog.posts.update_one({'view': 10}, {'$inc': {'view': 1}})   # $inc将view增加1,$set会将view设置成指定值
38         print(rest.matched_count)     # matched_count 匹配的次数
39         print(rest.modified_count)    # modified_count 修改成功的数据条数
40         # 修改多条数据
41         rest = self.db.blog.posts.update_many({}, {'$inc': {'view': 10}})   # 将所有的view增加10
42         print(rest.matched_count)
43         print(rest.modified_count)
44 
45     def delete(self):
46         """删除数据"""
47         # 删除一条数据
48         rest = self.db.blog.posts.delete_one({'view': 10})
49         print(rest.deleted_count)   # deleted_count 删除成功的数据条数
50         # 删除多条数据
51         rest = self.db.blog.posts.delete_many({'title': '新的标题'})
52         print(rest.deleted_count)
53 
54 
55 def main():
56     obj = TestMongo()
57     # rest = obj.add_one()
58     # rest = obj.get_more()
59     # for item in rest:
60     #     print(item)
61     # obj.update()
62     # obj.delete()
63 
64 
65 if __name__ == '__main__':
66     main()

猜你喜欢

转载自www.cnblogs.com/zuzhuangmengxiang/p/12603566.html