Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To retrieve distinct values in Python using MongoDB, first, we need to create a MongoClient object and specify the database and collection name. We can then use the distinct() method to get a list of distinct values for a specific field in our collection.

Here's an example code snippet:

from pymongo import MongoClient

# create MongoClient connection
client = MongoClient()

# select database and collection
db = client.mydatabase
mycollection = db.mycollection

# find distinct values for a specific field
distinct_values = mycollection.distinct("myfield")

# print the result
print(distinct_values)

In the above example, we are getting distinct values for the "myfield" field in the "mycollection" collection of the "mydatabase" database. The distinct values are stored in the "distinct_values" variable and printed to the console.