pymongo的简单使用

pymongo的简单使用

免费的资料,可以关注公众号:爬虫探索者或者pctansuo公众号私信001领取。私信mac相关软件也可以发送对应软件名。

安装pymongo

pip install -i https://mirrors.aliyun.com/pypi/simple pymongo

初始化

1.创建连接

import pymongo

client = pymongo.MongoClient(host="localhost", port=27017) # IP地址+端口号

db = client['test']  # 选择使用的数据库,不需要事先有数据库。
# 或者
db = client.test

collection = db['subjects'] # 指定集合
# 或者
collection = db.subjects

2.插入数据

好多资料上使用的还是inset函数,目前3.11不支持了!

  1. insert_one
    插入一条数据
collection.insert_one({'subject': 'coffEE', 'author': 'zhangsan', 'views': 30})
  1. insert_many
    插入多条数据
collection.insert_many(
    [
        {'subject': "coffee", 'author': "xyz", 'views': 50},
        {'subject': "Coffee Shopping", 'author': "efg", 'views': 5},
        {'subject': "Baking a cake", 'author': "abc", 'views': 90},
        {'subject': "Baking a cake", 'author': "abc", 'views': 90},
        {'subject': "baking", 'author': "xyz", 'views': 100},
        {'subject': "Café Con Leche", 'author': "abc", 'views': 200},
        {'subject': "Сырники", 'author': "jkl", 'views': 80},
        {'subject': "coffee and cream", 'author': "efg", 'views': 10},
        {'subject': "Cafe con Leche", 'author': "xyz", 'views': 10}
    ]
)

3.查询数据

3.1.基础查询

查询的操作比较多,更多操作可以参考官方手册https://www.mongodb.com/docs/v5.0/tutorial/query-documents/,实例配SQL语句讲解。

  1. find_one

查询一条数据,传入字典可以根据条件查询{'subject': 'Baking a cake'}最后返回的结果就是subject为Baking a cake的记录。

collection.find_one() # 返回的是一个字典类型的数据
# 打印结果:{'_id': ObjectId('65f922487ffe67451afe384f'), 'subject': 'coffEE', 'author': 'zhangsan', 'views': 30}
# 或者
collection.find_one({'subject': 'Baking a cake'})
# 打印结果:{'_id': ObjectId('65f922487ffe67451afe3852'), 'subject': 'Baking a cake', 'author': 'abc', 'views': 90}
  1. find

查询所有数据

# find函数返回的是一个pymongo.cursor.Cursor类对象
collection.find()
# 打印结果:<pymongo.cursor.Cursor object at 0x00000259D7020810>

2.1. 添加参数

其中$in表示包含,也就是说views属性值包含10和80的有哪些。

类似于SQL语句中的in操作

results = collection.find({'views': {'$in': [10, 80]}})
for result in results:  # 通过for循环获取封装为Cursor类的数据
    print(result)
比较符号例子描述
$in${‘in’: [10, 80]}表示查询出指定列的值在范围内的
$nin${‘nin’: [10, 80]}和$in相反,不包含的意思
$lt${‘views’: ${‘$lt’: 20}}返回views小于20的
$gt${‘views’: ${‘$gt’: 20}}返回views大于20的
$lte${‘views’: ${‘$lte’: 20}}小于等于
$gte${‘views’: ${‘$gte’: 20}}大于等于
$ne${‘views’: ${‘$ne’: 10}}不等于

2.2. 使用正则表达式查询

results = collection.find({'subject': {'$regex': '^c.*'}})
for result in results:
    print(result)

3.计数
python3.11版本的不再支持find().count(),需要使用estimated_document_count函数。

collection.estimated_document_count()

加条件的计数

collection.count_documents({'subject': {'$regex': '^c.*'}})

4.$text的用法
在使用$text查询的时候需要创建索引

collection.create_index({'索引列': 'text'})
collection.create_index({'subject': 'text'})
# 创建完成
collection.count_documents({'$text': {'$search': 'coffee'}})  # 计数
results = collection.find({'$text': {'$search': 'coffee'}})
for result in results:
    print(result)

4.排序

1.ASCEDING
按照指定列正序
2.DESCENDING
按照指定列逆序

results = collection.find().sort({'views': pymongo.ASCENDING})
for result in results:
    print(result)

5.偏移

逆序排序然后跳过前两个

print('-' * 50 + '偏移')
results = collection.find().sort({'views': pymongo.DESCENDING}).skip(2)
for result in results:
    print(result)

limit:跳过前两个然后取两个

print('-' * 50 + '偏移')
results = collection.find().sort({'views': pymongo.DESCENDING}).skip(2).limit(2)
for result in results:
    print(result)

6.更新数据

将name等于张三的第一条数据的性别改为

result = collection.update_one({'subject': 'coffEE'}, {'$set': {'views': 100}})
print(result)
# matched匹配到的
# modified修改的
print(result.matched_count, result.modified_count)
result = collection.update_many({'$text': {'$search': 'cake'}}, {'$set': {'views': 200}})
print(result)
for result in collection.find():
    print(result)

7.删除

result = collection.delete_one({'subject': 'Baking a cake'})
print(result)
result = collection.delete_many({'views': 10})
print(result)

完整代码

import pymongo

client = pymongo.MongoClient(host="localhost", port=27017)  # IP地址+端口号

db = client['test']  # 选择使用的数据库,不需要事先有数据库。
# 或者
# db = client.test

collection = db['subjects']
# 或者
# collection = db.subjects
# collection.insert_one({'subject': 'coffEE', 'author': 'zhangsan', 'views': 30})
# collection.insert_many(
#     [
#         {'subject': "coffee", 'author': "xyz", 'views': 50},
#         {'subject': "Coffee Shopping", 'author': "efg", 'views': 5},
#         {'subject': "Baking a cake", 'author': "abc", 'views': 90},
#         {'subject': "Baking a cake", 'author': "abc", 'views': 90},
#         {'subject': "baking", 'author': "xyz", 'views': 100},
#         {'subject': "Café Con Leche", 'author': "abc", 'views': 200},
#         {'subject': "Сырники", 'author': "jkl", 'views': 80},
#         {'subject': "coffee and cream", 'author': "efg", 'views': 10},
#         {'subject': "Cafe con Leche", 'author': "xyz", 'views': 10}
#     ]
# )

result = collection.find()
print(result)
print(collection.find_one({'subject': 'Baking a cake'}))
results = collection.find({'views': {'$in': [10, 80]}})
for result in results:
    print(result)
print('-' * 100)
results = collection.find({'subject': {'$regex': '^c.*'}})
for result in results:
    print(result)
print(collection.estimated_document_count())
print(collection.count_documents({'subject': {'$regex': '^c.*'}}))

# 在使用$text做查询的时候需要创建索引
collection.create_index({'subject': 'text'})
print(collection.count_documents({'$text': {'$search': 'coffee'}}))
for result in collection.find({'$text': {'$search': 'coffee'}}):
    print(result)

print('-' * 50 + '排序')
results = collection.find().sort({'views': pymongo.DESCENDING})
for result in results:
    print(result)


print('-' * 50 + '偏移')
results = collection.find().sort({'views': pymongo.DESCENDING}).skip(2).limit(2)
for result in results:
    print(result)


print('-' * 50 + '更新')
result = collection.update_one({'subject': 'coffEE'}, {'$set': {'views': 100}})
print(result)
# matched匹配到的
# modified修改的
print(result.matched_count, result.modified_count)
result = collection.update_many({'$text': {'$search': 'cake'}}, {'$set': {'views': 200}})
print(result)
for result in collection.find():
    print(result)


print('-' * 50 + '删除')
result = collection.delete_one({'subject': 'Baking a cake'})
print(result)
result = collection.delete_many({'views': 10})
print(result)

  • 30
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爬虫探索者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值