Sitemap

A Romp through MongoDB Atlas & Python 4

4 min readJun 27, 2024

--

Now let’s extract all the people in team blue whose last name is “Einstein”.

Here is the code:

########### THIS PART OF THE CODE REMAINS STATIC ################

#pymongo is the PyPI library we use to interface with MongoDB
from pymongo import MongoClient

# IMPORTANT +++ THESE YOU ALWAYS NEED +++
# (1) Connect to mongodb cluster using the connection string (ie. set up a "client")
# (2) Give mongodb the name of the database you want to access
# (3) Give mongodb the name of the collection within the database you want to access

#(1) This is the connection string
CONNECTION_STRING = "mongodb+srv://mongodbeducation:akRYE9B9ukLHaw8Z@cluster0.rikur45.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"

#(2) this is the database
this_database = 'people_db'

#(3) This is the collection
this_collection = 'people'

#Pass the connection string to MongoDB
client = MongoClient(CONNECTION_STRING)

#Pass the name of the database
dbname = client[this_database]

#Pass collection name
collection_name = dbname[this_collection]

########### END OF STATIC CODE ########################

# +++++++++++ HERE IS THE CHANGED CODE +++++++++++

#Let's find all the people who are members of the blue team
query01 = {"team":"blue"}
#And all the people whose name is Einstein
query02 = {"last_name":"Einstein"}

#Combine query01 & query02 using the $and operator
this_query = {"$and":[query01, query02]}
cursor = collection_name.find(this_query)

results_list = list(cursor)

# +++++++++++ END CHANGED CODE +++++++++++++++++

print(f'number of documents extracted: {len(results_list)}')

print('Extract from first 10 results')

for i, x in enumerate(results_list):
print(f'i = {i}')
print(f'{x['first_name']} {x['last_name']} is in team {x['team']}')
if i >= 9:
break

We combined two queries of the form:

{field name: value}

Using the $and operator

And the results:

number of documents extracted: 3
Extract from first 10 results
i = 0
Ulysses Einstein is in team blue
i = 1
Eugene Einstein is in team blue
i = 2
Martha Einstein is in team blue

Notice how we combined two queries using the “$and” operator. The $and operator takes a list. All conditions in the list must be met (all “true”) for the document to be included in the cursor list.

Get Steven Meyer’s stories in your inbox

Join Medium for free to get updates from this writer.

In our next we’re going to discuss a different way of achieving the same result using “aggregation” instead of find.

Now let’s find all people located in London, Berlin or Wagga Wagga. We’ll uses the $or operator.

##### Static part of code goes here ###############

#People who are located in London
query01 = {"city":"London"}

#People who are located in Berlin
query02 = {"city":"Berlin"}

#People who are located in Wagga Wagga
query03 = {"city":"Wagga Wagga"}


#Combine all queries with $or operator
this_query = {"$or":[query01, query02, query03]}
cursor = collection_name.find(this_query)

results_list = list(cursor)

# +++++++++++ END CHANGED CODE +++++++++++++++++

print(f'number of documents extracted: {len(results_list)}')

print('Extract from first 20 results')

for i, x in enumerate(results_list):
print(f'i = {i}')
print(f'{x['first_name']} {x['last_name']} lives in {x['city']}')
if i >= 19:
break

And here is the output:

number of documents extracted: 127
Extract from first 20 results
i = 0
Solomon Xavier lives in Wagga Wagga
i = 1
Alice Maxwell lives in London
i = 2
Una Benson lives in Berlin
i = 3
Tariq Feynman lives in Berlin
i = 4
Patricia Unger lives in London
i = 5
Deborah Johnson lives in Wagga Wagga
i = 6
Evelyn Evans lives in Berlin
i = 7
Felicity Garfield lives in Wagga Wagga
i = 8
Ruth Patterson lives in Berlin
i = 9
Qunicy Deng lives in Wagga Wagga
i = 10
Yolanda Tchaikovsky lives in Wagga Wagga
i = 11
Solomon Karloff lives in London
i = 12
Fred Morton lives in Berlin
i = 13
Amelia Evans lives in Berlin
i = 14
Una Du Toit lives in London
i = 15
Reuben Dawson lives in Berlin
i = 16
Yvette Quillan lives in Wagga Wagga
i = 17
Philip Lincoln lives in Wagga Wagga
i = 18
Eugene Kahn lives in Wagga Wagga
i = 19
Lynda Du Toit lives in London

Next we extract the people who have a bonus greater than 200000, a salary less than 100000 and were born in or after 1975.

Code:

##### Static part of code goes here ###############

#People with bonus > 200000
query01 = {"bonus":{"$gt":200000}}

#salary < 100000
query02 = {"salary":{"$lt":100000}}

#born in or after 1975
query03 = {"dob.year":{"$gte":1975}} #Note use of dot notation


this_query = {"$and":[query01, query02, query03]} #all 3 conditions must be satisfied
cursor = collection_name.find(this_query)

results_list = list(cursor)

# +++++++++++ END CHANGED CODE +++++++++++++++++

print(f'number of documents extracted: {len(results_list)}')

print('Extract from first 10 results')

for i, x in enumerate(results_list):
print(f'i = {i}')
print(f'{x['first_name']} {x['last_name']}:')
print(f'bonus: {x['bonus']} salary: {x['salary']}, Year of Birth: {x['dob']['year']}')
print()
if i >= 9:
break

And output:

number of documents extracted: 113
Extract from first 10 results
i = 0
Solomon Xavier:
bonus: 365000 salary: 99000, Year of Birth: 1979

i = 1
Solomon Dawson:
bonus: 334000 salary: 77000, Year of Birth: 2002

i = 2
Albert Nixon:
bonus: 272000 salary: 84000, Year of Birth: 2003

i = 3
Tariq Einstein:
bonus: 292000 salary: 93000, Year of Birth: 1981

i = 4
Una Cohen:
bonus: 360000 salary: 76000, Year of Birth: 2000

i = 5
Kenneth Potter:
bonus: 216000 salary: 76000, Year of Birth: 1986

i = 6
Felix Sayers:
bonus: 242000 salary: 85000, Year of Birth: 1998

i = 7
Jane Gavascar:
bonus: 333000 salary: 81000, Year of Birth: 1984

i = 8
Zelde Anderson:
bonus: 315000 salary: 80000, Year of Birth: 1979

i = 9
Theresa Dawson:
bonus: 237000 salary: 91000, Year of Birth: 1983

Next we shall consider the aggregate method. It has many advantages over find.

--

--