Python 数据库骚操作 — MongoDB

2018-11-0710:48:26编程语言入门到精通Comments2,447 views字数 4855阅读模式

MongoDB GUI 工具

首先介绍一款 MongoDB 的 GUI 工具 Robo 3T,初学 MongoDB 用这个来查看数据真的很爽。可以即时看到数据的增删改查,不用操作命令行来查看。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

Python 数据库骚操作 — MongoDB
Python 数据库骚操作 — MongoDB

PyMongo(同步)

可能大家都对 PyMongo 比较熟悉了,这里就简单介绍它的增删改查等操作。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

连接

# 普通连接
client = MongoClient('localhost', 27017)
client = MongoClient('mongodb://localhost:27017/')
#
# 密码连接
client = MongoClient('mongodb://username:password@localhost:27017/dbname')
db = client.zfdb
# db = client['zfdb']

test = db.test
复制代码

# 增加一条记录
person = {'name': 'zone','sex':'boy'}
person_id = test.insert_one(person).inserted_id
print(person_id)
复制代码
# 批量插入
persons = [{'name': 'zone', 'sex': 'boy'}, {'name': 'zone1', 'sex': 'boy1'}]
result = test.insert_many(persons)
print(result.inserted_ids)
复制代码

# 删除单条记录
result1 = test.delete_one({'name': 'zone'})
pprint.pprint(result1)
复制代码
# 批量删除
result1 = test.delete_many({'name': 'zone'})
pprint.pprint(result1)
复制代码

# 更新单条记录
res = test.update_one({'name': 'zone'}, {'$set': {'sex': 'girl girl'}})
print(res.matched_count)
复制代码
# 更新多条记录
test.update_many({'name': 'zone'}, {'$set': {'sex': 'girl girl'}})
复制代码

# 查找多条记录
pprint.pprint(test.find())

# 添加查找条件
pprint.pprint(test.find({"sex": "boy"}).sort("name"))
复制代码

聚合

如果你是我的老读者,那么你肯定知道我之前的骚操作,就是用爬虫爬去数据之后,用聚合统计结合可视化图表进行数据展示。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

aggs = [
    {"$match": {"$or" : [{"field1": {"$regex": "regex_str"}}, {"field2": {"$regex": "regex_str"}}]}}, # 正则匹配字段
    {"$project": {"field3":1, "field4":1}},# 筛选字段 
    {"$group": {"_id": {"field3": "$field3", "field4":"$field4"}, "count": {"$sum": 1}}}, # 聚合操作
]

result = test.aggregate(pipeline=aggs)
复制代码

例子:以分组的方式统计 sex 这个关键词出现的次数,说白了就是统计有多少个男性,多少个女性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

test.aggregate([{'$group': {'_id': '$sex', 'weight': {'$sum': 1}}}])
复制代码

聚合效果图:(秋招季,用Python分析深圳程序员工资有多高?文章配图)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

Python 数据库骚操作 — MongoDB
Python 数据库骚操作 — MongoDB

Motor(异步)

Motor 是一个异步实现的 MongoDB 存储库 Motor 与 Pymongo 的配置基本类似。连接对象就由 MongoClient 变为 AsyncIOMotorClient 了。下面进行详细介绍一下。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

连接

# 普通连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
# 副本集连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://host1,host2/?replicaSet=my-replicaset-name')
# 密码连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://username:password@localhost:27017/dbname')
# 获取数据库
db = client.zfdb
# db = client['zfdb']
# 获取 collection
collection = db.test
# collection = db['test']
复制代码

增加一条记录

添加一条记录。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_insert():
     document = {'name': 'zone','sex':'boy'}
     result = await db.test_collection.insert_one(document)
     print('result %s' % repr(result.inserted_id))
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())
复制代码
Python 数据库骚操作 — MongoDB

批量增加记录

添加结果如图所暗示。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_insert():
    result = await db.test_collection.insert_many(
        [{'name': i, 'sex': str(i + 2)} for i in range(20)])
    print('inserted %d docs' % (len(result.inserted_ids),))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())

复制代码
Python 数据库骚操作 — MongoDB

查找一条记录

async def do_find_one():
    document = await db.test_collection.find_one({'name': 'zone'})
    pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find_one())
复制代码
Python 数据库骚操作 — MongoDB

查找多条记录

查找记录可以添加筛选条件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_find():
    cursor = db.test_collection.find({'name': {'$lt': 5}}).sort('i')
    for document in await cursor.to_list(length=100):
        pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())

# 添加筛选条件,排序、跳过、限制返回结果数
async def do_find():
    cursor = db.test_collection.find({'name': {'$lt': 4}})
    # Modify the query before iterating
    cursor.sort('name', -1).skip(1).limit(2)
    async for document in cursor:
        pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())
复制代码
Python 数据库骚操作 — MongoDB" alt="查找多条记录" data-data-original="https://user-gold-cdn.xitu.io/2018/11/7/166ebe05b3709413?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" src="https://www.cainiaoxueyuan.com/wp-content/themes/begin/img/loading.png"height="20" data-width="516" data-height="98" />

统计

async def do_count():
    n = await db.test_collection.count_documents({})
    print('%s documents in collection' % n)
    n = await db.test_collection.count_documents({'name': {'$gt': 1000}})
    print('%s documents where i > 1000' % n)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_count())
复制代码
Python 数据库骚操作 — MongoDB" alt="统计" data-data-original="https://user-gold-cdn.xitu.io/2018/11/7/166ebe05c1d4fe0e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" src="https://www.cainiaoxueyuan.com/wp-content/themes/begin/img/loading.png"height="20" data-width="215" data-height="59" />

替换

替换则是将除 id 以外的其他内容全部替换掉。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_replace():
    coll = db.test_collection
    old_document = await coll.find_one({'name': 'zone'})
    print('found document: %s' % pprint.pformat(old_document))
    _id = old_document['_id']
    result = await coll.replace_one({'_id': _id}, {'sex': 'hanson boy'})
    print('replaced %s document' % result.modified_count)
    new_document = await coll.find_one({'_id': _id})
    print('document is now %s' % pprint.pformat(new_document))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_replace())
复制代码
Python 数据库骚操作 — MongoDB

更新

更新指定字段,不会影响到其他内容。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_update():
    coll = db.test_collection
    result = await coll.update_one({'name': 0}, {'$set': {'sex': 'girl'}})
    print('更新条数: %s ' % result.modified_count)
    new_document = await coll.find_one({'name': 0})
    print('更新结果为: %s' % pprint.pformat(new_document))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_update())
复制代码
Python 数据库骚操作 — MongoDB

删除

删除指定记录。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

async def do_delete_many():
    coll = db.test_collection
    n = await coll.count_documents({})
    print('删除前有 %s 条数据' % n)
    result = await db.test_collection.delete_many({'name': {'$gte': 10}})
    print('删除后 %s ' % (await coll.count_documents({})))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_delete_many())
复制代码
Python 数据库骚操作 — MongoDB

后记

MongoDB 的骚操作就介绍到这里,后面会继续写 MySQL 和 Redis 的骚操作。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

作者:zone
来源:掘金文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/7748.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/7748.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定