【mongodb】pymongo使用

发布时间 2023-05-31 00:17:13作者: passion2021

pymongo基本使用

import pymongo
from bson.objectid import ObjectId

# 连接方式1
client = pymongo.MongoClient(host='localhost', port=27017)

# 连接方式2
# client = pymongo.MongoClient('mongodb://localhost:27017/')

# 创建数据库
db = client['test']

# 创建集合
collection = db['students']

# 创建字典数据
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

# 插入单条
result = collection.insert_one(student)
print(result)

# 插入多条
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)

# 查询一个
result = collection.find_one({'age': 20})
print(type(result))
print(result)

# 使用bson查询
# bson称之为二进制的json -->  BSON对JSON的一大改进就是,它会将JSON的每一个元素的长度存在元素的头部
result = collection.find_one({'_id': ObjectId('6475f612bb7f540f86a499a3')})
print(type(result))
print(result)

# 查询多条
results = collection.find({'age': 20})
print(results)  # 返回一个cursor类型 相当于一个生成器
for result in results:
    print(result)

# 查询所有
results = collection.find()
for result in results:
    print(result)

# 返回指定条数
results = collection.find().limit(3)
for result in results:
    print(result)

# 条件查询
results = collection.find({'age': {'$gt': 20}})
for result in results:
    print(result)
'''
$gt 大于  $gte 大于等于  $ne 不等于
$lt 小于  $lte 小于等于
$in      在范围内
$nin     不在范围内
'''

# 支持正则匹配
results = collection.find({'name': {'$regex': '^M.*'}})
for result in results:
    print(result)

# 计数
count = collection.count_documents({'name': 'Mike'})
print(count)

count2 = collection.count_documents({})
print(count2)

# 排序
results = collection.find().sort('name', pymongo.ASCENDING)  # 升序 pymongo.ASCENDING  倒序 pymongo.DESCENDING
print([result['name'] for result in results])

# 偏移
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)  # 忽略前两个元素
print([result['name'] for result in results])

# 组合使用skip\limit
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)  # 先偏移两个 再获取两个
print([result['name'] for result in results])

# 数据量千万、亿级别,不要使用偏移,如下是解决方案,这时需要记录好上次查询的_id。
from bson.objectid import ObjectId
collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})

# 更新
condition = {'name': 'Mike'}
student = collection.find_one(condition)
print(student)
student['age'] = 24
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)  # 匹配的数据条数  影响的数据条数
'''
使用$set操作符号:
    这样可以只更新 student 字典内存在的字段。
    如果原先还有其他字段,则不会更新,也不会删除。
'''

# 将年龄大于20的人,年龄自增1
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})  # 这里会将第一条匹配到的数据 其年龄自增1
print(result)
print(result.matched_count, result.modified_count)

# 将所有年龄大于20的人,年龄自增1
condition = {'age': {'$gt': 19}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

# 删除
result = collection.delete_one({'name': 'Jordan'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)