Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use count distinct in pymongo? [closed]

I have a sql:

select field2, count(distinct field1) from table group by field2;

How to achieve this sql in pymongo?

like image 870
Bdfy Avatar asked Dec 06 '11 08:12

Bdfy


2 Answers

You can accomplish these kinds of queries with the pymongo driver by using the .group() function.

db.table.group(["field1"], {}, {"count":0},"function(o, p){p.count++}" )

This will group together distinct values of "field1" and increment a counter to track the number of occurrences of each.

like image 194
mpobrien Avatar answered Nov 16 '22 09:11

mpobrien


I've found this resource to be very helpful when working on doing conversions from SQL to Mongo SQL to Mongo Mapping Chart

In this case you would be looking like something similar to:

db.users.group({key: {age: true},
initial: {count: 0}, 
reduce: function (obj, prev) { prev.count++;} } )

Since you have a bit more complex logic here you need to use the reduce function. Honestly you should read a bit more into this to fully understand exactly what is going on here. Map Reduce

like image 22
Petrogad Avatar answered Nov 16 '22 11:11

Petrogad