Open In App

Python MongoDB - distinct()

Last Updated : 04 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

  • key (string): field name for which you want to find distinct values.
  • filter (optional, dict): a query to filter which documents to consider when finding distinct values.

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

distinct-database
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

distinct-output
Snapshot of Terminal showing Output of Distinct method

Related Article:


Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy