Python MongoDB Query
- Previous Page MongoDB Find
- Next Page MongoDB Sort
Filter de resultaten
Bij het zoeken naar documenten in de collectie, kun je query-objecten gebruiken om de resultaten te filteren.
find()
De eerste parameter van de methode is het query-object, gebruikt om de zoekopdracht te beperken.
Example
Zoek documenten met de adres "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 perform advanced queries, you can use modifiers as values in the query object.
For example, to find documents where the "address" field starts with the letter "S" or higher (in alphabetical order), please use the greater modifier:{"$gt": "S"}
:
Example
Find documents where the address starts with the letter "S" or higher:
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)
Use regular expressions to filter
You can also use regular expressions as modifiers.
Regular expressions can only be used for string queries.
If you only want to find documents where the "address" field starts with the letter "S", please use a regular expression {"$regex": "^S"}
:
Example
Find documents where the address starts with the letter "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)
- Previous Page MongoDB Find
- Next Page MongoDB Sort