MongoEctoLite - Ecto with MongoDB

MongoEctoLite aims to be a simple bridge from Ecto Changesets to MongoDB.

Please note: this project is in early days and should be considered a tech preview at this point.

Almost all Phoenix examples use Ecto, and LiveView uses Changesets extensively. Unfortunately there is not an actively maintained solution for using Ecto with MongoDB.

MongoEctoLite implements a subset of Ecto.Repo functions, specifically those used by phx.gen.live and phx.gen.auth. It supports schemas with map, embeds_one, embeds_many, and schemaless.

Example:

  defmodule MyCollection do
    use Ecto.Schema
    import Ecto.Changeset

    @primary_key {:_id, :binary_id, autogenerate: false}
    schema "my_collection" do
      field(:name, :string)
      field(:child, :map)

      timestamps()
    end

    def changeset(item, attrs) do
      item
      |> cast(attrs, [:name, :child])
      |> validate_required([:name, :child])
    end
  end

  attrs = %{name: "some name", child: %{name: "some child name"}}

  {:ok, my_collection} =
    %MyCollection{}
    |> MyCollection.changeset(attrs)
    |> Repo.insert()

  results = Repo.all(Schema, %{name: "some name"})

Dynamic repositories are also supported:

MyCollection.with_dynamic_repo(conn, fn ->
  MyCollection.all(Schema)
end)

Special thanks to @zookzook for continuing work on elixir-mongodb-driver.

3 Likes

Out of curiosity what drove the decision to go this route instead of creating an Ecto adapter for Mongo DB?

1 Like

Thanks for the question.

I need the smallest amount of functionality to support my current project. Particularly porting the Query DSL to Mongo is more work than I can take on at the moment.

It looks really impressive so far. Keep up the good work :).

1 Like