The distinct() method

Introduction to MongoDB in Python

Donny Winston

Instructor

An exceptional laureate

db.laureates.find_one({"prizes.2": {"$exists": True}})
{'_id': ObjectId('5baacf97f35b632bbe12c1ad'),
 'born': '0000-00-00',
 'died': '0000-00-00',
 'firstname': ('Comité international de la Croix Rouge'
               '(International Committee of the Red Cross)'),
 'gender': 'org',
 'id': '482',
 'prizes': [{'affiliations': [[]],
   'category': 'peace',
   'share': '1',
   'year': '1917'},
  {'affiliations': [[]], 'category': 'peace',
   'share': '1', 'year': '1944'},
  {'affiliations': [[]], 'category': 'peace',
   'share': '2', 'year': '1963'}]}
Introduction to MongoDB in Python

Using .distinct()

db.laureates.distinct("gender")
['male', 'female', 'org']
  • A convenience method for a common aggregation (like count_documents)
  • We will learn how to create custom aggregations in Chapter 4
  • distinctaggregation is efficient if there is a collection index on the field
  • We will learn how to create an index in Chapter 3
  • No index needed here: collection fits in memory, has ≤ 1,000 documents
Introduction to MongoDB in Python

.distinct() with dot notation

db.laureates.find_one({"prizes.2": {"$exists": True}})
{'_id': ObjectId('5baacf97f35b632bbe12c1ad'),
 'born': '0000-00-00',
 'died': '0000-00-00',
 'firstname': ('Comité international de la Croix Rouge'
               '(International Committee of the Red Cross)'),
 'gender': 'org',
 'id': '482',
 'prizes': [{'affiliations': [[]],
   'category': 'peace',
   'share': '1',
   'year': '1917'},
  {'affiliations': [[]], 'category': 'peace',
   'share': '1', 'year': '1944'},
  {'affiliations': [[]], 'category': 'peace',
   'share': '2', 'year': '1963'}]}
db.laureates.distinct("prizes.category")
['physics', 'chemistry', 'peace',
 'medicine', 'literature', 'economics']
['physics', 'chemistry', 'peace', 'medicine', 'literature', 'economics']
Introduction to MongoDB in Python

Let's practice!

Introduction to MongoDB in Python

Preparing Video For Download...