Create a Web API with MongoDB
Tags: mongodb, dotnet, api, csharp
Published: 2024-06-14 16:45:18

Hello guys!
Today I challenged myself to learn a little bit about MongoDB, so I created an API that will connect to a MongoDB database.

## What is MongoDB?

MongoDB is a NOSQL database and NOSQL means "Not Only SQL". This is because MongoDB is not only a relational database. NOSQL can store unstructured data.

MongoDB is a document database. It stores data in a type of JSON format called BSON. A record in MongoDB is a document, which is a data structure composed of key value pairs similar to the structure of JSON objects.
And this documents are stored in collections (you can compare a collection like as a table in SQL Relational databases). And all this collections are stored in a database!

## MongoDB Setup

To start using MongoDB the first thing that you need is the MongoDB "engine". For that I recommend using a image container and run that image in the docker container.

After pull the image and run it, you need a way to interact with the database. I used MongoDB Compass.

## MongoDB integration
To integrate your MongoDB database with your .NET API, you'll need to install the following nuget package:
- MongoDB.Driver
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zg4r360duwi5qw20rij9.png)

I have in the Model folder a Event class that represent the document in MongoDB.
Important thing to notice here is there is specific Data Annotations to handle MongoDB data.

```
public class Event
{
    [BsonId]
    public Guid EventId { get; set; }

    [BsonElement("title")]
    public string Title { get; set; }

    [BsonElement("description")]
    public string Description { get; set; }

    [BsonElement("location")]
    public string Location { get; set; }

    [BsonElement("date")]
    public DateTime Date { get; set; }

    [BsonElement("users")]
    public List<Guid> Users { get; set; } // List of users associated with the event
}
```

The next thing you need is to establish connection to the MongoDB. In this example I create a factory class to do that.

```
public class MongoDbConnection : IMongoDbConnection
{
    private readonly IConfiguration _configuration;

    public MongoDbConnection(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IMongoDatabase GetDatabase()
    {
        var connectionString = _configuration.GetSection("MyDb").GetValue<string>("ConnectionString");
        var databaseName = _configuration.GetSection("MyDb").GetValue<string>("DatabaseName");

        var url = MongoUrl.Create(connectionString);
        var client = new MongoClient(url);
        var database = client.GetDatabase(databaseName);

        return database;
    }
}
```
And on the appsettings.json file, I added the connection string:

```
"MyDb": {
  "ConnectionString": "mongodb://localhost:27017",
  "DatabaseName": "Eventsdb",
  "EventsCollectionName": "events"
}
```

I created a repository class to interact with the database:

```
public class EventsRepository : IEventsRepository
{
    private readonly IMongoDbConnection _connection;
    private readonly IMongoCollection<Event> _collection;

    public EventsRepository(IMongoDbConnection connection)
    {
        _connection = connection;

        var database = _connection.GetDatabase();
        _collection = database.GetCollection<Event>("events");
    }

    public async Task<bool> CreateEvent(Event evento)
    {
        try
        {
            await _collection.InsertOneAsync(evento);
            return true;
        }
        catch (Exception)
        {
            throw;
        }
    }

    public async Task<bool> DeleteEvent(Guid id)
    {
        var filterDefinition = Builders<Event>.Filter.Eq(a => a.EventId, id);
        var result = await _collection.DeleteOneAsync(filterDefinition);
        return result.DeletedCount > 0;
    }

    public async Task<List<Event>> GetAllEvents()
    {
        return await _collection.Find(Builders<Event>.Filter.Empty).ToListAsync();
    }

    public async Task<Event> GetEventById(Guid id)
    {
        var filterDefinition = Builders<Event>.Filter.Eq(a => a.EventId, id);
        return await _collection.Find(filterDefinition).FirstAsync();
    }

    public async Task<bool> UpdateEvent(Event evento)
    {
        var filterDefinition = Builders<Event>.Filter.Eq(a => a.EventId, evento.EventId);
        var result = await _collection.ReplaceOneAsync(filterDefinition, evento);
        return result.ModifiedCount > 0;
    }
}
```

And that's it guys, a simple use case of using a api with mongodb. I hope you liked it, stay tuned for more!