Skip to content

Commit 28ab716

Browse files
authored
Update 4. Aggregation Pipelines: Let the Server Do It For You.md
1 parent 293fada commit 28ab716

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Introduction to MongoDB in Python/4. Aggregation Pipelines: Let the Server Do It For You.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,3 +214,19 @@ Possible Answers
214214
Instructions
215215
- [x] In your aggregation pipeline pipeline, use the "gender" field to limit results to people (that is, not organizations).
216216
- [x] Count prizes for which the laureate's "bornCountry" is not also the "country" of any of their affiliations for the prize. Be sure to use field paths (precede a field name with "$") when appropriate.
217+
```py
218+
pipeline = [
219+
# Limit results to people; project needed fields; unwind prizes
220+
{"$match": {"gender": {"$ne": "org"}}},
221+
{"$project": {"bornCountry": 1, "prizes.affiliations.country": 1}},
222+
{"$unwind": "$prizes"},
223+
224+
# Count prizes with no country-of-birth affiliation
225+
{"$addFields": {"bornCountryInAffiliations": {"$in": ["$bornCountry", "$prizes.affiliations.country"]}}},
226+
{"$match": {"bornCountryInAffiliations": False}},
227+
{"$count": "awardedElsewhere"},
228+
]
229+
230+
print(list(db.laureates.aggregate(pipeline)))
231+
```
232+
[{'awardedElsewhere': 478}]

0 commit comments

Comments
 (0)