Python MongoDB Query

Filter the results

When searching for documents in the collection, you can use the query object to filter the results.

find() The first parameter of the method is the query object, which is used to limit the search.

Example

Find documents 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)

Run Instance

Advanced Query

For 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 (alphabetically), please use the greater modifier:{"$gt": "S"}:

Example

Find documents with addresses starting 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)

Run Instance

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 with addresses starting 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)

Run Instance