Databases

Elixir MongoDB

Using MongoDB

Elixir MongoDB uses mongodb_driver for document data.

Introduction to MongoDB in Elixir

MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is known for its flexibility and scalability, making it a popular choice for modern applications. In Elixir, we can use the mongodb_driver library to interact with MongoDB databases efficiently.

Setting Up the mongodb_driver

To start using MongoDB with Elixir, you need to add the mongodb_driver to your project. This can be done by including it in your mix.exs file.

Here's how you can set it up:

After adding the dependency, run mix deps.get to install the driver.

Connecting to MongoDB

Once you have installed the mongodb_driver, you can connect to your MongoDB instance. Here's a basic example of how to establish a connection:

This code snippet connects to a MongoDB instance running locally on the default port (27017) and database named my_database.

Inserting Documents

With the connection established, you can now insert documents into your MongoDB database. Here's an example of how to insert a document:

In this example, a document containing user information is inserted into the users collection.

Querying Documents

Querying documents in MongoDB using Elixir is straightforward. You can use the following code to find documents:

This code retrieves all documents from the users collection where the city field is New York.

Updating Documents

Updating documents is also simple. Use the following code to update a document:

This code updates the age field of the document where the name is John Doe.

Deleting Documents

To delete documents, you can use the following code:

This code removes the document from the users collection where the name is John Doe.

Previous
PostgreSQL
Next
Redis