You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Introduction to MongoDB in Python/3. Get Only What You Need, and Fast.md
+27-2Lines changed: 27 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -24,8 +24,10 @@ will fetch documents where the field 'name' ***starts with "Py".***
24
24
25
25
> In this exercise, you will use regular expressions, projection, and list comprehension to collect the full names of laureates whose initials are "G.S.".
26
26
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.
29
31
30
32
```py
31
33
# Find laureates whose first name starts with "G" and last name starts with "S"
@@ -36,3 +38,26 @@ docs = db.laureates.find(
36
38
print(docs[0])
37
39
```
38
40
```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]
0 commit comments