Python-data-access-python-mongodb-query
提供:Dev Guides
Python MongoDB-クエリ
- 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'}