Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct values from PyMongo

In MongoDB I have a dataset of store data. Using PyMongo I am finding all of the distinct/unique values in a collection

for testy in collection.distinct('stores'):
print(testy)

I can also find a subset of badly spelt stores I'm interested in

for testy in collection.find({'stores': {'$in': ['Aldi','ALDI','aldi']}}):

What I want to do is find the unique in this subset

According to the MongoDB docs

db.runCommand ( { distinct: "inventory", key: "item.sku", query: { dept: "A"} } )

Tried lots of combinations adding the query doing the $in but can't get it to work.

like image 933
Townheadbluesboy Avatar asked May 13 '15 12:05

Townheadbluesboy


People also ask

How do I show distinct values in MongoDB?

MongoDB – Distinct() Method In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.

Can we use distinct with find in MongoDB?

Both the find and distinct operations are very useful when it comes to retrieving data from MongoDB. The find operation returns the data all at once or according to the query and projection. The distinct operation has a special functionality of retrieving unique values of a specified field.

What is MongoClient in PyMongo?

Python PyMongo MongoClient allows Developers to establish a connection between their Python application and MongoDB to manage data in a NoSQL Database. Python PyMongo MongoClient makes it easier for Developers to access all the features of the NoSQL Database and build a scalable and flexible Python application.

How do I run a distinct query in MongoDB compass?

You can do this via aggregation framework in Compass, using $unwind and $group. The $unwind is performed to create a unique document for each element in the target array, which enables the $addToSet operator in the $group stage to then capture the genres as distinct elements.


1 Answers

What you are looking for is distinct

for testy in collection.find().distinct('stores'):
    print(testy)

or

for testy in collection.distinct('stores', {'dept': 'A'}):
    print(testy)
like image 57
styvane Avatar answered Sep 28 '22 21:09

styvane