How can I use aggregate in mongodb lib

Hi, I’m trying to do some aggregation with this adapter GitHub - elixir-mongo/mongodb: MongoDB driver for Elixir.

I’m tring to translate this mongo query:

db.trip.aggregate([{$group: {_id : "$city.name", count: {$sum: 1}}}])

That actually works in mongo shell and bring this results:

{ “_id” : { “name” : “City1” }, “count” : 212 }

{ “_id” : { “name” : “City2” }, “count” : 1200 }

{ “_id” : { “name” : “City3” }, “count” : 789 }

{ “_id” : { “name” : “City4” }, “count” : 540 }

{ “_id” : { “name” : “City5” }, “count” : 333 }

I’m tryin’ to use Mongo.aggregate but I don’t have clear the sintax, could anyone help me with this?

The set up of the lib is ok, I have some find queries and works find and I can render the responses correctly, It’s just I cannot figure it out how do I have to write the aggregate sentences with this adapter.

Thanks in advance.

Mongo.aggregate(pid, "trip", [%{"$group" => %{ "_id" => "$city.name", "count" => %{ "$sum" => 1}}}])

That should give you what you are looking for.

1 Like

Thanks a lot!!!

this working perfectly for me. I was missing square brackets before the first level map.

cheers.