美文网首页
mongodb和python交互

mongodb和python交互

作者: 小袋鼠cf | 来源:发表于2018-12-30 23:36 被阅读0次

    import pymongo

    创建数据库连接
    """
    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:217017/'
    )

    需要账号密码登录

    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':'斯巴达克斯3',
    'actor':'未知',
    'type':'动作',
    'info':'古罗马传记',
    }
    document2 = {
    'title': '斯巴达克斯4',
    'actor': '未知',
    'type': '动作',
    'info': '古罗马传记',
    }
    result = col_name.insert([document1,document2])
    result = col_name.insert_many([document1,document2])
    print(result)

    def delete_data():

    # multi = False:删除一条,multi = True:删除多条

     result = col_name.remove({'title':'斯巴达克斯'},multi=False)
     print(result)
    
     result = col_name.delete_one({'title':'斯巴达克斯'})
     print(result.deleted_count)
    

    result = col_name.delete_many({'title': '斯巴达克斯2'})
    print(result.deleted_count)
    from bson import ObjectId
    def update_data():
    """

    :return:
    """#upsert=False:表示如果要更新的文档不在集合下,则什么都不做,
    upsert = ture:
    result = col_name.update(
        {'title':'斯巴达克斯1'},
        {'$set':{'info':'1712b'}},
    )
     print(result)
     col_name.update(
         {'title':'斯巴达克斯3'},
       {'name':'小米','gender':'女','age':18}
    )
     col_name.update(
         {'name': '小米'},
         {'$set':{'age':20,'class':'1712b'}}
     )
    
    save方法可以保存也可以更新数据,如果ID不存在,则插入一条新数据。
    
    result = col_name.save(
        {
            '_id':   ObjectId("5c26011b0a7f0a2b00f9041a"),
            'title':' this is a girl',
            'info':'1712b',
            'age':30,
            'name':'丽丽'
         }
    )
    print(result )
    

    def find_data():
    """
    查找
    :return:
    """
    result = col_name.find({})
    print(result)
    print([i for i in result ])
    #根据条件查找所有
    result = col_name.find({'name':'丽丽'})
    print([i for i in result])
    result = col_name.find_one({'name':'丽丽'})
    print(result)
    result = col_name.find({}).skip(2).limit(3).sort('age',1)
    for i in result:
    print(i)

    result = col_name.find({}).skip(2).limit(3).sort('age',1)
    for i in result:
        print(i)
    #limit:限制
    #skip:跳过
    #sort:排序
    

    if name == 'main':
    insert_data()
    delete_data()
    update_data()
    find_data()

    相关文章

      网友评论

          本文标题:mongodb和python交互

          本文链接:https://www.haomeiwen.com/subject/wugblqtx.html