A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-mongodb-distinct/ below:

Python MongoDB - distinct() - GeeksforGeeks

Python MongoDB - distinct()

Last Updated : 04 Jul, 2025

distinct() method in MongoDB is used to retrieve all unique values for a specified field from a collection. In Python, you can use this method with PyMongo to filter out duplicates and get a list of distinct values across documents. This is helpful when you want to find all unique fields without repeating values.

Syntax
collection.distinct(key, filter=None)

Parameters :

Let's create a sample collection: python
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
mydb = client['database']
mycollection = mydb['myTable']

# Insert sample documents
documents = [
    {"_id": 1, "dept": "A", "item": {"code": "012", "color": "red"}, "sizes": ["S", "L"]},
    {"_id": 2, "dept": "A", "item": {"code": "012", "color": "blue"}, "sizes": ["M", "S"]},
    {"_id": 3, "dept": "B", "item": {"code": "101", "color": "blue"}, "sizes": "L"},
    {"_id": 4, "dept": "A", "item": {"code": "679", "color": "black"}, "sizes": ["M"]}
]

mycollection.insert_many(documents)

# Print inserted documents
print("Inserted Documents:\n")
for doc in mycollection.find():
    print(doc)

Output

Snapshot of Terminal showing Collection created Example:

In this Example, distinct() method is used to return unique values of different fields from the collection.

Python
# 1. Return distinct values for the 'dept' field
print(mycollection.distinct('dept'))

# 2. Return distinct values for the embedded field 'item.color'
print(mycollection.distinct('item.color'))

# 3. Return distinct values for the array field 'sizes'
print(mycollection.distinct("sizes"))

# 4. Return distinct 'item.code' where 'dept' is 'B'
print(mycollection.distinct("item.code", {"dept": "B"}))

Output

Snapshot of Terminal showing Output of Distinct method

Related Article:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4