Python MongoDB Query

Filter the Result – Үр дүнг шүүх #

When finding documents in a collection, you can filter the result by using a query object.

Цуглуулга доторх баримт бичгүүдийг хайхдаа та лавлах объект ашиглан үр дүнг шүүх боломжтой.

 

The first argument of the find() method is a query object, and is used to limit the search.

find() арга нь хайлтыг хязгаарлахад ашигладаг лавлах объектыг эхний аргументаар авдаг.

Example – Жишээ #

Find document(s) with the address “Park Lane 38”:

Хаяг баримт бичигт “Park Lane 38” орсонг хайх:  

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address""Park Lane 38" }
mydoc = mycol.find(myquery)
for x in mydoc:
  print(x)

Advanced Query – Нарийвчилсан асуулга #

To make advanced queries you can use modifiers as values in the query object.

Нарийвчилсан асуулга хийхийн тулд асуулгын объект дахь утгууд болгон хувиргагчдыг ашиглаж болно.

E.g. to find the documents where the “address” field starts with the letter “S” or higher (alphabetically), use the greater than modifier: {"$gt": "S"}:

Жишээлбэл, “address” талбарын утга “S” үсгээр эхэлсэн эсвэл түүнээс хойших(Цагаан толгойн дарааллаар) бичиг баримтуудыг олохын тулд томоос бага утга оруулах “$gt” утга хэрэглэнэ: {“$gt”: “S”}.

Example – Жишээ #

Find documents where the address starts with the letter “S” or higher:

Хаяг дотрох “S”-ээр эхэлж S-ын дараах цагаан толгой үсэг байх бүх баримт бичгийг хайж олох:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$gt""S" } }
mydoc = mycol.find(myquery)
for x in mydoc:
  print(x)

Filter With Regular Expressions – Тогтмол илэрхийлэлтэй шүүлтүүр #

You can also use regular expressions as a modifier.

Та тогтмол илэрхийлэл ашиглан илүү нарийн шүүлтүүр хийж болно.

Regular expressions can only be used to query strings.

Тогтмол илэрхийлэл нь зөвхөн тэмдэгт мөрүүд хэрэглэдэг.

To find only the documents where the “address” field starts with the letter “S”, use the regular expression {"$regex": "^S"}:

“Хаяг” талбарын “S”-ээр эхэлсэн үгийг тогтмол илэрхийлэл ашиглаж олох:  {"$regex": "^S"}

Example – Жишээ #

Find documents where the address starts with the letter “S”:

Хаягт “S” үсгээр эхэлсэн баримт бичгүүдийг олох: 

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$regex""^S" } }
mydoc = mycol.find(myquery)
for x in mydoc:
  print(x)

Powered by BetterDocs

Leave a Reply