Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB- rename()
Next article icon

distinct() method in MongoDB is used toretrieve 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
frompymongoimportMongoClientclient=MongoClient("mongodb://localhost:27017/")mydb=client['database']mycollection=mydb['myTable']# Insert sample documentsdocuments=[{"_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 documentsprint("Inserted Documents:\n")fordocinmycollection.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' fieldprint(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:


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp