在MongoDB中使用Python进行范围查询

2023-04-15 00:00:00 python mongodb 查询

在MongoDB中,可以使用Python驱动程序pymongo进行范围查询。范围查询是根据指定的字段的值在一定范围内查询文档的过程。下面是详细步骤和代码演示:
1.安装pymongo驱动程序

pip install pymongo

2.连接MongoDB数据库并获取集合

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['test_db']
collection = db['test_collection']

3.插入测试数据

data = [{"name": "pidancode.com", "age": 20},
        {"name": "pandaboy", "age": 25},
        {"name": "pandabear", "age": 30},
        {"name": "pandagirl", "age": 35}]
collection.insert_many(data)

4.范围查询
可以使用MongoDB的$gt、$gte、$lt和$lte操作符来执行范围查询。

# 查询age大于20的文档
result = collection.find({"age": {"$gt": 20}})
for i in result:
    print(i)
# 查询age大于等于20的文档
result = collection.find({"age": {"$gte": 20}})
for i in result:
    print(i)
# 查询age小于30的文档
result = collection.find({"age": {"$lt": 30}})
for i in result:
    print(i)
# 查询age小于等于30的文档
result = collection.find({"age": {"$lte": 30}})
for i in result:
    print(i)

5.删除测试数据

collection.delete_many({})

完整代码演示:

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['test_db']
collection = db['test_collection']
data = [{"name": "pidancode.com", "age": 20},
        {"name": "pandaboy", "age": 25},
        {"name": "pandabear", "age": 30},
        {"name": "pandagirl", "age": 35}]
collection.insert_many(data)
result = collection.find({"age": {"$gt": 20}})
for i in result:
    print(i)
result = collection.find({"age": {"$gte": 20}})
for i in result:
    print(i)
result = collection.find({"age": {"$lt": 30}})
for i in result:
    print(i)
result = collection.find({"age": {"$lte": 30}})
for i in result:
    print(i)
collection.delete_many({})

相关文章