📜  Python MongoDB-查询

📅  最后修改于: 2020-11-07 09:01:07             🧑  作者: Mango


使用find()方法进行检索时,可以使用查询对象过滤文档。您可以将指定所需文档条件的查询作为参数传递给此方法。

经营者

以下是MongoDB查询中使用的运算符列表。

Operation Syntax Example
Equality {“key” : “value”} db.mycol.find({“by”:”tutorials point”})
Less Than {“key” :{$lt:”value”}} db.mycol.find({“likes”:{$lt:50}})
Less Than Equals {“key” :{$lte:”value”}} db.mycol.find({“likes”:{$lte:50}})
Greater Than {“key” :{$gt:”value”}} db.mycol.find({“likes”:{$gt:50}})
Greater Than Equals {“key” {$gte:”value”}} db.mycol.find({“likes”:{$gte:50}})
Not Equals {“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

以下示例在年龄大于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'}