Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo- How can I have distinct values for a field along with other query parameters

I am using pymongo and want to have distinct values for a field such that I can also pass other query parameters. For example, I have entries like:

{    id = "my_id1"    tags: [tag1, tag2, tag3],    category: "movie", } {    id = "my_id2"    tags: [tag3, tag6, tag9],    category: "tv", } {    id = "my_id3"    tags: [tag2, tag6, tag8],    category: "movie", } 

So I want to have all distinct tags under movie category. Can anyone please guide how can I achive this using pymongo. In mongo javascript shell, I issued db.mycoll.distinct('tags', {category: "movie"}) and it worked just fine. But when I do the same in pymongo it raises error. I guess it is not supported in pymongo. Any idea though how can such a task be achieved.

like image 946
Sushant Gupta Avatar asked Oct 14 '12 06:10

Sushant Gupta


People also ask

How can I get distinct values from a field in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

How do I use distinct aggregation in MongoDB?

You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large. The question was to get the city with MOST zip codes for each state, not to get the actual zip codes.

Which command gives all the 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.

What is the use of distinct in MongoDB?

distinct() considers each element of the array as a separate value. For instance, if a field has as its value [ 1, [1], 1 ] , then db. collection. distinct() considers 1 , [1] , and 1 as separate values.


1 Answers

You have to make the distinct call on the cursor returned from a find instead of on the collection:

tags = db.mycoll.find({"category": "movie"}).distinct("tags") 
like image 98
JohnnyHK Avatar answered Sep 19 '22 16:09

JohnnyHK