Python MongoDB - Kueri

Saat mengambil menggunakan find()metode, Anda dapat memfilter dokumen menggunakan objek kueri. Anda dapat meneruskan kueri yang menentukan kondisi untuk dokumen yang diperlukan sebagai parameter untuk metode ini.

Operator

Berikut adalah daftar operator yang digunakan dalam kueri di MongoDB.

Operasi Sintaksis Contoh
Persamaan {"key": "value"} db.mycol.find ({"by": "tutorials point"})
Kurang dari {"key": {$ lt: "value"}} db.mycol.find ({"suka": {$ lt: 50}})
Kurang Dari Sama Dengan {"key": {$ lte: "value"}} db.mycol.find ({"suka": {$ lte: 50}})
Lebih besar dari {"key": {$ gt: "value"}} db.mycol.find ({"suka": {$ gt: 50}})
Lebih Dari Sama {"kunci" {$ gte: "value"}} db.mycol.find ({"suka": {$ gte: 50}})
Tidak Sama {"key": {$ ne: "value"}} db.mycol.find ({"suka": {$ ne: 50}})

Contoh 1

Contoh berikut mengambil dokumen dalam koleksi yang namanya 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)

Keluaran

Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}

Contoh2

Contoh berikut mengambil dokumen dalam koleksi yang nilai usianya lebih dari 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)

Keluaran

Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}