I have a sql:
select field2, count(distinct field1) from table group by field2;
How to achieve this sql in pymongo?
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.
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
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