elixir-mongo / mongodb

MongoDB driver for Elixir
Apache License 2.0
571 stars 156 forks source link

Calling Mongo when using mongodb_ecto how to get the topology_pid #379

Closed hdecolle closed 1 year ago

hdecolle commented 1 year ago

Hi I am using:

{:mongodb_ecto, "~> 1.0.0"}

The repo config is:

config :my_app, MyApp.Repo,
adapter: Mongo.Ecto,
database: "test_db",
hostname: "mongodb"

I want to count and group a status field. In ecto this can be done with something like that:

query = from c in MySchema,
select: {c.status, count()},
group_by: c.status

Repo.all(query)

This does not work, yet which is in the docs and ok. In mongdb shell it works with:

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

So I want to call Mongo.aggregate directly, but I have problems getting topology_pid.

When I try to use MyApp.Repo.pool() as documented here this does not work, because the pool() function does not exist.

How to I get that pid, or how can I perform that aggregate.

Any help is welcome.

I also tried to find the pid with Process.whereis(MyApp.Repo) which did not work.

When I start a new process with:

{:ok, conn} = Mongo.start_link(url: "URL")

The function is working but it is not returning what I was thinking.

hdecolle commented 1 year ago

The function is working now, I got back a cursor and forgot to pipe that into Enum.to_list

Now the only question is how to get to the pid.

ankhers commented 1 year ago

I think the answer is supposed to be MyApp.Repo.Pool, but that doesn't appear to be working.

This is ugly, and I am not going to guarantee that it is going to work all the time, but you can use the following code in order to get the pid of the actual mongo process.

MyApp.Repo |> :sys.get_state() |> get_in([Access.elem(3), Access.elem(1), Mongo, Access.elem(1)])
hdecolle commented 1 year ago

Thank you, its ugly but it works.

Aside: I hope that I can also use that to access a mongodb on DigitalOcean.

ankhers commented 1 year ago

It shouldn't matter where your mongo database is hosted. As long as you are able to connect to it, the above should work in order to get the pid from the ecto adapter.

I am closing this as I believe we having a "working" solution. If there is anything else, please feel free to either reopen this issue or create a new one.