mongodb——python的交互

mongodb-python的交互:
#安装pymongo:pip install pymongo
import pymongo
1.链接mongod的服务
2.库和表的名字:有数据会自动建库建表
3.插入数据
import pymongo
try:
    #1.链接mongod的服务
    mongo_py=pymongo.MongoClient(username='A',password='123456')
    #2.库和表的名字:有数据会自动建库建表
    db=mongo_py['four']
    collection=db['stu']
    # collection=mongo_py['four']['stu']
    # collection=mongo_py.four.stu
    #3.插入数据
    # one={'name':'张三','age':'16'}
    #插入多条数据
    many=[
        {'name': '小康', 'age': 24},
        {'name': '小兰', 'age': 34},
        {'name': '李四', 'age': 18},
        {'name': '小顶', 'age': 29}
    ]
    # collection.insert_one(one)
    # collection.insert_many(many)
    #collections.insert() :既可以插入一条,也可以插入多条数据

    #4.删除数据  delete_one:仅删除符合条件的第一条数据
    # collection.delete_one({'age':'18'})
    # collection.delete_many({}):删除多条数据  {}:表示删除所有数据

    #4.修改数据 update
    # collection.update_one({'name':'小康'},{'$set':{'name':'小时'}})
    # collection.update_many({'age':{'$lt':26}},{'$set':{'gender':'true'}})
    # collection.update_many({'age':{'$gt':26}},{'$set':{'gender':'false'}})

    #5.查询数据
    # res=collection.find({'gender':'true'})
    # print(res.__iter__().__next__())
    res=collection.find_one({'gender':'true'})
    print(res)

except Exception as e:
    print(e)
finally:
    mongo_py.close()

猜你喜欢

转载自www.cnblogs.com/wuweixiong/p/12640924.html
今日推荐