mongoBD--python、mongodb交互

import pymongo
from pymongo.results import DeleteResult
from bson.objectid import ObjectId

创建数据库连接
"""
 host=None,:ip 127.0.0.1
 port=None,:端口 27017
"""
mongo_client = pymongo.MongoClient(
    host='127.0.0.1',port=27017
)
# mongo_client = pymongo.MongoClient(
#     'mongodb://127.0.0.1:27017/'
# )
#需要账号密码登录
# mongo_client = pymongo.MongoClient(
#     'mongodb://username:password@ip:port'
# )
选择数据库
db = mongo_client['mongotest']
# db = mongo_client.mongotest
选择数据库下的集合
col_name = db['test']
插入数据
def insert_data():
    document1 = {
            'title': 'this is a gril',
            'info': '1712B',
            'age': 18,
            'name': 'zhaowenzhu'
        }
    document2 = {
            'title': 'this is a gril',
            'info': '1712B',
            'age': 15,
            'name': 'zhaowenzhu'
        }
    document3 = {
        'title': 'this is a gril',
        'info': '1712B',
        'age': 12,
        'name': 'zhaowenzhu'
    }

    # result = col_name.insert(document1)
    # result = col_name.insert_one(document1)
    # print(result) #5c25e4be11575e4a4b0d0a91

    result = col_name.insert([document1,document2,document3])
    # result = col_name.insert_many([document1,document2])
    print(result)  # [ObjectId('5c25e50a11575e4a9cb2b91e'), ObjectId('5c25e50a11575e4a9cb2b91f')]
    print([str(i) for i in result])
def delete_data():
    #multi=True:可以删除多条数据,multi=False:删除一条 
    result = col_name.remove({'title':'斯巴达克斯'},multi=False)
    print(result) #{'ok': 1.0, 'n': 1}

    #删除一条
    result = col_name.delete_one({'title':'斯巴达克斯'})
    print(result.deleted_count)
    #删除多条
    result = col_name.delete_many({'title':'斯巴达克斯2'})
    print(result.deleted_count)
更新
def update_data():
    """
    update
    :return:
    """
    #指定属性更新
    #multi=False:默认情况下,只会修改一条
    # result = col_name.update(
    #     {'title':'斯巴达克斯5'},
    #     {'$set':{'info':'1712B'}}
    # )
    # print(result)
    #全文档更新
    #multi=False:默认情况下,只会修改一条
    #upsert=False:表示如果要更新的文档不在集合下,则什么都不做
    #upsert=True:表示如果要更新的文档不在集合下,则会插入一条新的文档
    # result = col_name.update(
    #     {'title':'斯巴达克斯5'},
    #     {'name':'张三','gender':'女','age':18}
    # )
    # print(result)

    #update_one和update_many使用的时候一定要记得添加
    #$set,
    # result = col_name.update_one(
    #     {'name':'田真'},
    #     {'$set':{'age':20,'class':'1712B'}}
    # )
    # print(result) #pymongo.results.UpdateResult
    # col_name.update_many()
save方法可以保存也可以更新数据
    from bson.objectid import ObjectId
    #save会做全文的那个更新
    # result = col_name.save(
    #     {
    #         '_id':ObjectId("5c26c01a11575e0bec8f0395"),
    #         'title':'this is a gril',
    #         'info':'1712B',
    #         'age':20,
    #         'name':'zhaowenzhu'
    #     }
    # )
    # print(result)
    #如果_id不存在,则插入一条新数据
    result = col_name.save(
        {
            '_id': '1234567',
            'title': 'this is a gril',
            'info': '1712B',
            'age': 20,
            'name': 'zhaowenzhu'
        }
    )
    print(result)
查找
def find_data():
    """
    查找
    :return:
    """
    #查找所有
    # result = col_name.find({})
    # print(result) #pymongo.cursor.Cursor object
    # print([i for i in result])
    #
    # #根据条件查找
    # result = col_name.find({'name':'zhaowenzhu'})
    # print([i for i in result])
    #
    # #查找一条
    # result = col_name.find_one({'name':'zhaowenzhu'})
    # print(result) #返回的是一个dict

    #limit:限制查询
    #skip:跳过
    #sort:排序 1:升序 -1:降序
    result = col_name.find({}).skip(2).limit(3).sort('age',-1)
    #要根据多个字段排序
    result = col_name.find({}).skip(2).limit(3).sort([('age',1),('years',1)])
    for i in result:
        print(i)

if __name__ == '__main__':

    #insert_data()
    # delete_data()
    # update_data()
    find_data()

你可能感兴趣的:(mongoBD--python、mongodb交互)