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({“like”:{$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

下面的例子是在一个集合中检索年龄值大于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'}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程