bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Python/Databases in Python
Python•Databases in Python

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.

Example

Find document(s) with the address "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"} :

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)

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"} :

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

Python MySQL Where

Next

Python MySQL Order By

This chapter

Overview
23

Lessons

49m

Read time

1. Python MySQL2. Python MongoDB3. Python MySQL Create Database4. Python MongoDB Create Database5. Python MySQL Create Table6. Python MongoDB Create Collection7. Python MySQL Insert Into Table8. Python MongoDB Insert Document9. Python MySQL Select From10. Python MongoDB Find11. Python MySQL Where12. Python MongoDB Query13. Python MySQL Order By14. Python MongoDB Sort15. Python MySQL Delete From By16. Python MongoDB Delete Document17. Python MySQL Drop Table18. Python MongoDB Drop Collection19. Python MySQL Update Table20. Python MongoDB Update21. Python MySQL Limit22. Python MongoDB Limit23. Python MySQL Join

On this page

Filter the ResultAdvanced QueryFilter With Regular Expressions