- Python MongoDB 教程
- Python MongoDB - 主页
- Python MongoDB - 介绍
- Python MongoDB - 创建数据库
- Python MongoDB - 创建集合
- Python MongoDB - 插入文档
- Python MongoDB - 查找
- Python MongoDB - 查询
- Python MongoDB - 排序
- Python MongoDB - 删除文档
- Python MongoDB - 删除集合
- Python MongoDB - 更新
- Python MongoDB - 限制
- Python MongoDB 有用资源
- Python MongoDB - 速查指南
- Python MongoDB - 有用资源
- Python MongoDB - 讨论
Python MongoDB - 查询
在使用 find() 方法检索时,你可以使用查询对象来过滤文档。你可以将指定所需文档条件的查询作为该方法的参数进行传递。
运算符
以下是在 MongoDB 中查询中使用的运算符列表。
| 运算 | 语法 | 示例 |
|---|---|---|
| 相等 | {"key" : "value"} | db.mycol.find({"by":"tutorials point"}) |
| 小于 | {"key" :{$lt:"value"}} | db.mycol.find({"likes":{$lt:50}}) |
| 小于或等于 | {"key" :{$lte:"value"}} | db.mycol.find({"likes":{$lte:50}}) |
| 大于 | {"key" :{$gt:"value"}} | db.mycol.find({"likes":{$gt:50}}) |
| 大于或等于 | {"key" {$gte:"value"}} | db.mycol.find({"likes":{$gte:50}}) |
| 不等于 | {"key":{$ne: "value"}} | db.mycol.find({"likes":{$ne:50}}) |
示例 1
以下示例检索集合中名为 sarmista 的文档。
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sdsegf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc1 in coll.find({"name":"Sarmista"}):
print(doc1)
输出
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
示例 2
以下示例检索集合中 age 值大于 26 的文档。
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['ghhj']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc in coll.find({"age":{"$gt":"26"}}):
print(doc)
输出
Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
广告