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

redfloyd
Greetings fellow alchemists ! I have started to write an open-source interpreter in Elixir (GitHub - nicolasdilley/dwarf-interpreter: Th...
New
annad
I’m posting this for developers who are totally new to Phoenix like myself. This is all probably obvious to more skilled Phoenix develope...
New
AstonJ
..or as and when you can think of one :icon_cool: This thread my also be of interest: What took you way too long to figure out? :003:
New
niku
I write an article Parameterized testing with ExUnit.The key concept is using ExUnit.Case.register_test/4 such as ExUnit.start() defmod...
New
nelsonic
Complete beginners Todo List Tutorial in Phoenix 1.5.3 (latest and greatest): https://github.com/dwyl/phoenix-todo-list-tutorial It’s a...
New
berts-4865
Here is a quick guide to uploading a file from the browser to DO spaces. It is crude, but will hopefully save sometime time and frustrat...
New
crockwave
To integrate dropdown menus in a Phoenix Liveview app, you can use a combination of js, Hooks, CSS and your .leex and .ex code. You can...
New
jshprentz
Geoffrey Lessel’s 2019 book, Phoenix in Action, was written for Phoenix 1.4. I found that the book’s code examples did not match the cur...
New
pinksynth
Whenever tests have to interact with an Ecto.Repo, sometimes it’s necessary to test a few different branches or paths that data can take....
New
caspg
Hi everyone, I recently implemented a real-time search feature in a Phoenix application using LiveView and Tailwind, and I wanted to sha...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement