1. 程式人生 > >python操作三大主流資料庫(8)python操作mongodb資料庫②python使用pymongo操作mongodb的增刪改查...

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()