Skip to content

Commit 5863b7a

Browse files
authored
Update 3. Get Only What You Need, and Fast.md
1 parent 401316f commit 5863b7a

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

Introduction to MongoDB in Python/3. Get Only What You Need, and Fast.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@ will fetch documents where the field 'name' ***starts with "Py".***
2424

2525
> In this exercise, you will use regular expressions, projection, and list comprehension to collect the full names of laureates whose initials are "G.S.".
2626
27-
- [x] 1. First, use regular expressions to fetch the documents for the laureates whose "firstname" starts with "G" and whose "surname" starts with "S".
28-
- [x] 2. Use projection and adjust the query to select only the "firstname" and "surname" fields.
27+
- [x] 1) First, use regular expressions to fetch the documents for the laureates whose "firstname" starts with "G" and whose "surname" starts with
28+
"S".
29+
- [x] 2) Use projection and adjust the query to select only the "firstname" and "surname" fields.
30+
- [x] 3) Iterate over the documents, and for each document, concatenate the first name and the surname fields together with a space in between to obtain full names.
2931

3032
```py
3133
# Find laureates whose first name starts with "G" and last name starts with "S"
@@ -36,3 +38,26 @@ docs = db.laureates.find(
3638
print(docs[0])
3739
```
3840
```py
41+
# Use projection to select only firstname and surname
42+
docs = db.laureates.find(
43+
filter={"firstname": {"$regex": "^G"},
44+
"surname": {"$regex": "^S"}},
45+
projection=["firstname", "surname"])
46+
47+
48+
# Print the first document
49+
print(docs[0])
50+
```
51+
```py
52+
# Use projection to select only firstname and surname
53+
docs = db.laureates.find(
54+
filter= {"firstname" : {"$regex" : "^G"},
55+
"surname" : {"$regex" : "^S"} },
56+
projection= ["firstname", "surname"] )
57+
58+
# Iterate over docs and concatenate first name and surname
59+
full_names = [doc["firstname"] + " " + doc["surname"] for doc in docs]
60+
61+
# Print the full names
62+
print(full_names)
63+
```

0 commit comments

Comments
 (0)