zookzook

zookzook

Elixir and MongoDB

If you want to use the MongoDB in your next Killer-App-Project, but you did not dare ask because otherwise many would advise you to use Postgres, then you are right here. I won’t talk about choosing the right database. I will show how to use the MongoDB with Elixir. I assume that you already know the MongoDB and can use the Mongo Shell.

The first starting point are the official documentation pages of the driver. You can choose between two drivers:

I will add some more examples. But for now I published two simple crud examples to get an idea how to use the MongoDB driver. It is very simple.

In the example we just create, read, update and delete the following document:

def create_vcard() do
	%{
		firstname: "Alexander",
		lastname: "Abendroth",
		contact: %{
			email: "alexander.abendroth@campany.de",
			telephone: "+49 111938947373",
			mobile: "+49 222192938383",
			fax: "+49 3332929292"
		},
		addess: %{
			street: "Fasanenweg 5",
			postal_code: "12345",
			city: "Berlin",
			country: "de"
		}
	}
end

And here is our first CRUD example:

def example_1() do

	{:ok, top} = Mongo.start_link(url: "mongodb://localhost:27017/db-1")
	
	result = Mongo.insert_one(top, "people", create_vcard())

	IO.puts "#{inspect result}\n"

	result = Mongo.find_one(top, "people", %{})
	IO.puts "#{inspect result}\n"

	result = Mongo.update_one(top, "people", %{lastname: "Abendroth"}, ["$set": ["address.postal_code": "20000"]])
	IO.puts "#{inspect result}\n"

	result = Mongo.find_one(top, "people", %{"contact.email": "alexander.abendroth@campany.de"})
	IO.puts "#{inspect result}\n"

	result = Mongo.delete_one(top, "people", %{lastname: "Abendroth"})
	IO.puts "#{inspect result}\n"

end

We create a connection to the MongoDB-Instance listening von port 27001 and use the db-1

  1. We insert the document and get a result the ID: {:ok, %Mongo.InsertOneResult{acknowledged: true, inserted_id: #BSON.ObjectId<5d526a8f306a5f10851a0134>}}

  2. We are searching for the first document and got the inserted document back: %{"_id" => #BSON.ObjectId<5d526a8f306a5f10851a0134>, "addess" => %{"city" => "Berlin", "country" => "de", "postal_code" => "12345", "street" => "Fasanenweg 5"}, "contact" => %{"email" => "alexander.abendroth@campany.de", "fax" => "+49 3332929292", "mobile" => "+49 222192938383", "telephone" => "+49 111938947373"}, "firstname" => "Alexander", "lastname" => "Abendroth"}

  3. We update the postal code: {:ok, %Mongo.UpdateResult{acknowledged: true, matched_count: 1, modified_count: 1, upserted_ids: []}}

  4. We search again but search for the email: %{"_id" => #BSON.ObjectId<5d526a8f306a5f10851a0134>, "addess" => %{"city" => "Berlin", "country" => "de", "postal_code" => "12345", "street" => "Fasanenweg 5"}, "address" => %{"postal_code" => "20000"}, "contact" => %{"email" => "alexander.abendroth@campany.de", "fax" => "+49 3332929292", "mobile" => "+49 222192938383", "telephone" => "+49 111938947373"}, "firstname" => "Alexander", "lastname" => "Abendroth"}

  5. We delete the document: {:ok, %Mongo.DeleteResult{acknowledged: true, deleted_count: 1}}

The mongodb driver has the following features:

  • Supports MongoDB versions 3.2, 3.4, 3.6, 4.0
  • Connection pooling (through DBConnection 2.x)
  • Streaming cursors
  • Aggregation pipeline
  • Replica sets
  • Support for SCRAM-SHA-256 (MongoDB 4.x)
  • Support for change streams api (See)
  • Support for bulk writes (See)

I will try to add some more examples which show a special feature or how to the driver for some interesting use cases. But be patient I do this in my free time :slight_smile:

Most Liked Responses

hauleth

hauleth

Any reason why this is better than existing drivers like this one? I mean that this is great project, but what was lacking in others and why not expand existing drivers instead of creating new one?

zookzook

zookzook

Look here:

hauleth

hauleth

And mongodb? You have said you have forked that one, but there is no rationale why you needed to fork at all.

Where Next?

Popular in Guides/Tuts Top

benwilson512
Correct if me I’m wrong, as best I can tell there aren’t any reasons to use mix run --no-halt in production vs releases. The marginal val...
New
ben-pr-p
https://github.com/ben-pr-p/elixir-phoenix-parcel-example Hey all! I put together a starter-pack / instructions to set up Phoenix with t...
New
hlx
Typed my very first blog post ever, hope it will help some people https://henricus.xyz/roll-your-own-email-password-authentication-with-...
New
OvermindDL1
Ran across this recently, it’s a set of cheatsheet inforgraphic things of the OTP behaviours on the BEAM: https://github.com/Telichkin/o...
New
zachallaun
Hey friends, wanted to share a tiny shell script I’ve been using to start Livebook with easy access to either a running production server...
New
georgeguimaraes
Another cool plugin for Neovim, GitHub - jmbuhr/otter.nvim: Just ask an otter! 🦦 · GitHub makes it possible to run linters for embedded c...
New
danschultzer
I wrote this blog post based on our experiences setting up continuous delivery for our first production umbrella Phoenix app. Coming from...
New
jtormey
Hello! Having written a lot of LiveView code, I’ve made some VS Code snippets to speed up writing callbacks for LiveViews and LiveCompon...
New
Morzaram
Hey guys I’ve made a guide on how to connect Quill to Phoenix. For the sake of formatting it might be easier to view it on my Notion Doc...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement