pymongo

作者: Yinqiang | 来源:发表于2021-01-13 20:20 被阅读0次

安装

pip install pymongo -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn

API参考

API参考网站

链接数据库

def login_db(user:string, pws:string, db_name:string, host:string='localhost', port:int=27017) -> None:
    '''
    使用身份验证链接MongoDB,进入并返回指定库。
    '''
    client = MongoClient(host, port)
    db = mgclient['admin']
    db.authenticate(user, pws)
    db = client[db_name]
    return db

指定集合

db = login_db('username', 'passwd', 'db_test')
collection = db['the_collection_name']

插入记录

collection.insert_one({
    'code': code,
    'date': '2021-01-12',
    'price': 100.0,
})

# items = [{...}, {...}]
collection.insert_many(items)

条件查询

rs = collection.find({'code': '600000'})
for r in rs:
    print(r)

# 之看某些项
rs = collection.find(filter={'code': '600000'}, {'date':1, 'price':1})

# 排序,升序:1;降序:-1
rs = collection.find(filter={'code': '600000'}, sort=[('date': -1)])

# 个数限制
rs = collection.find(filter={'code': '600000'}, sort=[('date': -1)], limit=10)

更新记录

# replace是替换整个,update可以更新部分字段
rs = collection.update_one(filter={'code': '600000'}, update={'$set': {'price': 101.0}})

# 有则更新,无则插入
rs = collection.update_one(filter={'code': '600000'},
                           update={'$set': {'code': '600000', 'date': '2021-01-12', 'price': 101.0}},
                           upsert=True)

删除记录

# 数据是宝贵的,建议给记录打标记来“删除”

# 单条
rs = collection.delete_one(filter={'date': '2021-01-13'})

# 多条
rs = collection.delete_many(filter={'date': '2021-01-13'})

查记录数量

count = count_documents(filter={'code': '600000'})

根据字段名获得集合中改字段值种类的列表

values = collection.distinct('code')

相关文章

网友评论

      本文标题:pymongo

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