pymongo(二)-查询数据

281 阅读1分钟
# coding=utf-8

import pymongo
from bson.objectid import ObjectId

# 初始化连接
client = pymongo.MongoClient(host='localhost', port=27017)

# 指定book数据库
db = client['book']

# 指定集合(类似于数据库中的表)
collection = db['biquge']

# 查询数据
results = collection.find({"name": "雪中悍刀行"})
print(results)  # 结果是cursor类型,<pymongo.cursor.Cursor object at 0x000002027A8DBDC0>,相当于一个生成器
for result in results:
    print(result)

# 查看有几条数据
count = collection.count_documents({"name": "雪中悍刀行"})
print(count)

# 数据升降序
r = collection.find().sort('name', pymongo.ASCENDING)  # 升序,降序用DESCENDING
print([i for i in r])

# 限制查询个数
rc = collection.find({"name": "雪中悍刀行"}).limit(1)  # 只查询一条数据
print([i for i in rc])

# 偏移
rc1 = collection.find({"name": "雪中悍刀行"}).skip(2)  # 忽略前两个元素,获取第三个
print([i for i in rc1])

# 当数据较大的时候(千万,亿),不要使用大偏移量来查询数据,防止内存溢出,建议使用以下方法
rc2 = collection.find({'_id': {'$gt': ObjectId("61c1469582efaeb690729ebc")}})  # 这里需要记录好上次查询的_id
print([i for i in rc2])