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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With