Elixir 和 mongodb 聚合

Elixir and mongodb aggregation

我已经设置了一个 mongodb,其中包含一个具有以下结构的集合:

{ "_id" : "some_id", "city" : { "name" : "City1" }}

我用 elixir 1.9.2 和 phoenix 开始了一个项目,我已经设置了 {:mongodb, "~> 0.5.1"}

我已经在 phoenix 中设置了一些 find 查询,所以我与来自 phoenix 的 mongodb 的连接工作正常。

编辑: 这些查询已经对我有用:

def get_trip_list() do


{:ok, conn} = Mongo.start_link(url:"mongodb://localhost:27017/myaguila")

    cursor = Mongo.find(conn, "trip", %{})

    cursor
    |> Enum.to_list()
  end
def get_total_count() do
    {:ok, conn} = Mongo.start_link(url: "mongodb://localhost:27017/myaguila")
    cursor = Mongo.count(conn, "trip", %{})
    {:ok, total} = cursor
    {:total_trips, total}
  end

但现在我需要构建一个聚合查询来计算每个城市出现的次数,我真的不明白如何使用 phoenix[= 的 mongodb 管道45=]

我直接在 mongo 的 shell 中写了一个查询(我尝试并成功了)这样:

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

然后给我带来那些结果:

{ "_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 }

所以我需要将这个 mongo 查询翻译成长生不老药语言。

(不太了解,但我发现我不使用 Ecto)

这与长生不老药的预期结果相同。

这是图书馆的文档

https://hexdocs.pm/mongodb/readme.html#contributing

提前致谢。

看:)

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

mongodb 查询结果

{ "_id" : { "name" : "City1" }, "count" : 3 }
{ "_id" : { "name" : "City2" }, "count" : 2 }

这是解决方案:

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

我在第一级地图前漏掉了方括号。

感谢有兴趣的朋友