python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查
python操作mongodb数据库②python使用pymongo操作mongodb的增删改查
文档http://api.mongodb.com/python/current/api/index.html
http://api.mongodb.com/python/current/api/pymongo/collection.html
1.安装python操作mongodb的程序
pip install pymongo
验证是否安装成功
C:\Users\ajie>python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import pymongo
连接数据库
方式1:简写
>>> from pymongo import MongoClient
>>> client = MongoClient()
方式2:指定端口和地址
>>> client2 = MongoClient('localhost', 27017)
方式3:使用URI
>>> client3 = MongoClient('mongodb://localhost:27017/')
获取简单信息
>>> dir(client) ['HOST', 'PORT', '_BaseObject__codec_options', '_BaseObject__read_concern', '_BaseObject__read_preference', '_BaseObject__write_concern', '_MongoClient__all_credentials', '_MongoClient__cursor_manager', '_MongoClient__default_database_name', '_MongoClient__index_cache', '_MongoClient__index_cache_lock', '_MongoClient__kill_cursors_queue', '_MongoClient__lock', '_MongoClient__options', '_MongoClient__reset_server', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache_credentials', '_cache_index', '_cached', '_constructor_args', '_database_default_options', '_event_listeners', '_get_socket', '_get_topology', '_is_writable', '_kill_cursors_executor', '_process_periodic_tasks', '_purge_credentials', '_purge_index', '_repr_helper', '_reset_on_error', '_reset_server_and_request_check', '_send_message_with_response', '_server_property', '_socket_for_reads', '_socket_for_writes', '_topology', '_topology_settings', 'address', 'arbiters', 'close', 'close_cursor', 'codec_options', 'database_names', 'drop_database', 'event_listeners', 'fsync', 'get_database', 'get_default_database', 'is_locked', 'is_mongos', 'is_primary', 'kill_cursors', 'local_threshold_ms', 'max_bson_size', 'max_idle_time_ms', 'max_message_size', 'max_pool_size', 'max_write_batch_size', 'min_pool_size', 'next', 'nodes', 'primary', 'read_concern', 'read_preference', 'secondaries', 'server_info', 'server_selection_timeout', 'set_cursor_manager', 'unlock', 'write_concern'] >>> client.PORT 27017 >>> client.database_names() ['admin', 'config', 'local', 'students']
Mongodb关闭了还可以再次连接,是因为内部有连接池
使用pymongo操作mongo数据库的增删改查:
#coding:utf-8 from datetime import datetime from pymongo import MongoClient class MongoTest(object): def __init__(self): self.client = MongoClient() self.db = self.client['blog'] def add_one(self): '''添加单条数据''' # 造数据 # for i in range(3): # post = { # 'title':"人民代表大会提出将提高个税起征点"+str(i), # 'content':"非常好的建议,有利于民生"+str(i), # 'x':i, # 'create_at': datetime.now() # } # self.db.blog.posts.insert_one(post) # 添加单条数据 post = { 'title':"人民代表大会提出将提高个税起征点", 'content':"非常好的建议,有利于民生", 'x':18, 'create_at': datetime.now() } return self.db.blog.posts.insert_one(post) def get_one(self): '''获取单条数据''' return self.db.blog.posts.find_one() def get_more(self): '''获取多条数据''' return self.db.blog.posts.find() def update(self): ''' 修改数据 ''' # 将x为1的文档改为x+3 # res = self.db.blog.posts.update_one({'x':1},{'$inc':{'x':3}}) # print(res.matched_count) # 将所有的值都增加20 return self.db.blog.posts.update_many({}, {'$inc':{'x':20}}) def delete(self): '''删除数据''' # 删除x为1的1条数据 # res = self.db.blog.posts.delete_one({'x':0}) # print(res.deleted_count) # 删除x为1的多条数据 res = self.db.blog.posts.delete_many({'x':1}) print(res.deleted_count) def main(): mon = MongoTest() res = mon.add_one() # print(res.inserted_id) # res = mon.get_one() # print(res['title']) # res = mon.get_more() # for i in res: # print(i['title']) # res = mon.update() # print(res.matched_count) mon.delete() if __name__ == "__main__": main()