MQL – Querying MongoDB

Query MongoDB

In [1]:

#Find document with address "Park Lane 38"
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["valdb01"]
mycol = mydb["customers"]

myquery = { "address": "Park Lane 38" }

mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)
{'_id': ObjectId('6138618356e0542d940db71e'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('6138663a6461436a279a77da'), 'name': 'Ben', 'address': 'Park Lane 38'}

Find the documents where the “address” field starts with the letter “S” or higher (alphabetically),

use the greater than modifier: {“$gt”: “S”}:

In [2]:

#Find documents where the address starts with the letter "S" or higher:
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["valdb01"]
mycol = mydb["customers"]

myquery = { "address": { "$gt": "S" } }

mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)
{'_id': ObjectId('6138618356e0542d940db718'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('6138618356e0542d940db71b'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('6138618356e0542d940db71d'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('6138618356e0542d940db721'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('6138663a6461436a279a77d4'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('6138663a6461436a279a77d7'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('6138663a6461436a279a77d9'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('6138663a6461436a279a77dd'), 'name': 'Viola', 'address': 'Sideway 1633'}

Regular expressions can only be used to query strings

Find only the documents where the “address” field starts with the letter “S”,

use the regular expression {“$regex”: “^S”}:

In [3]:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["valdb01"]
mycol = mydb["customers"]

myquery = { "address": { "$regex": "^S" } }

mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)
{'_id': ObjectId('6138618356e0542d940db71b'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('6138618356e0542d940db721'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('6138663a6461436a279a77d7'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('6138663a6461436a279a77dd'), 'name': 'Viola', 'address': 'Sideway 1633'}

In [ ]:

 

Advertisement