Using MongoGogo: An ORM-Like Approach to MongoDB in C# .Net Core

謝夜喵
4 min readMay 20, 2024

--

MongoDB.Driver is challenging

MongoDB has long interacted with C# through the official MongoDB.Driver, allowing developers to efficiently use this NoSQL database in .NET applications.

However, while the MongoDB.Driver is powerful, it can sometimes be abstract`to use, especially for novice developers. To address this issue, this article introduces a package called MongoGogo, which acts as a wrapper around the MongoDB.Driver.

How MongoGogo looks like?

Assume your MongoDB cluster contains three databases: FirstDatabase, SecondDatabase, andOtherDatabase as shown in the image below.

My cluster

In MongoGogo, you would represent this setup as follows:

public class MongoContext : GoContext<MongoContext>
{
public MongoContext(MongoClientSettings settings) : base(settings)
{
}

[MongoDatabase("FirstDatabase")]
public class FirstDatabase { }

[MongoDatabase("SecondDatabase")]
public class SecondDatabase { }

[MongoDatabase("OtherDatabase")]
public class OtherDatabase { }
}

Furthermore, if there is a collection User in FirstDatabase ,

A collection called User in FirstDatabase

the MongoGogo model would look like this:

[MongoCollection(typeof(MongoContext.FirstDatabase), "User")]
public class UserEntity : GoDocument
{
}

As shown in the images and code, MongoGogo emphasizes a type-safedevelopment approach. Unlike the MongoDB.Driver, which only provides type safety at the collection level, MongoGogo ensures type safety at the database level by relying on type definitions rather than database names.

Getting Started with MongoGogo

Step 1: Add the MongoGogo Package

dotnet add package MongoGogo

Step 2: Create a Context

Next, create a context class that inherits from GoContext<TContext>. Notice that TContextmust be the class type itself.

Here's an example:

public class MongoContext : GoContext<MongoContext>
{
public MongoContext(MongoClientSettings settings) : base(settings)
{
}

[MongoDatabase("FirstDatabase")]
public class FirstDatabase { }

[MongoDatabase("SecondDatabase")]
public class SecondDatabase { }

[MongoDatabase("OtherDatabase")]
public class OtherDatabase { }
}

Step 3: Configure the Context in Program.cs

In your Program.cs file, add the context to the services collection. You can either use a connection string directly:

builder.Services.AddMongoContext(new MongoContext("your connectionString here"));

Or use the MongoClientSettings provided by the official MongoDB driver:

builder.Services.AddMongoContext(new MongoContext(MongoClientSettings.FromUrl(new MongoUrl("your connectionString here"))));

Step 4: Define Your Entities

Finally, create your own entities and specify their collections using attributes. Here’s an example for a User collection in FirstDatabase:

[MongoCollection(typeof(MongoContext.FirstDatabase), "User")]
public class UserEntity : GoDocument
{
public string Name { get; set; }

public int Age { get; set; }

public UserSecret Secret { get; set; }
}

public class UserSecret
{
public string Secret { get; set; }
}

Integration with .NET Core

In this section, we will demonstrate how to create a web API to access your database using MongoGogo.

.NET Core’s dependency injection (DI) system is incredibly powerful, and MongoGogo integrates seamlessly with it, making it easy to access collections such as User.

You can obtain MongoGogo’s collection object using DI with the IGoCollection interface:

[ApiController]
public class MainController : ControllerBase
{
private readonly IGoCollection<UserEntity> _collection;

public MainController(IGoCollection<UserEntity> collection)
{
this._collection = collection;
}
}

You can then use this collection object to perform database operations. For example, here is how you can use it to add a new user:

public class MainController : ControllerBase
{
private readonly IGoCollection<UserEntity> _collection;

public MainController(IGoCollection<UserEntity> collection)
{
this._collection = collection;
}

[HttpPost("AddUser")]
public async Task<IActionResult> AddUser()
{
UserEntity userEntity = new UserEntity
{
Name = "Jerry",
Age = 23,
Secret = new UserSecret
{
Secret = "28v&zmpv4p"
}
};
await _collection.InsertOneAsync(userEntity);

return Ok();
}
}

Conclusion

MongoGogo offers a robust and intuitive way to interact with MongoDB in your .NET Core applications. Here are some key advantages of using MongoGogo:

  • Type-Safe Development: Ensures type safety at both the collection and database levels, reducing runtime errors and improving code reliability.
  • Seamless Integration with .NET Core: Leverages .NET Core’s powerful dependency injection system, making it easy to manage and access your MongoDB collections.
  • Structured and Maintainable Code: Uses a clear, attribute-driven model for defining database contexts and entities, resulting in clean and maintainable code.
  • Simplified Database Management: Allows you to manage multiple databases within a single context, enhancing organization and accessibility.
  • Efficiency and Flexibility: Enables developers to focus on core application features without getting bogged down by boilerplate code, thanks to its efficient setup and usage patterns.

Whether you’re a seasoned developer or new to MongoDB and .NET Core, MongoGogo provides the tools and flexibility you need to build scalable and maintainable applications. By following the steps outlined in this guide, you can quickly set up MongoGogo and start taking advantage of its powerful features.

In summary, MongoGogo is more than just a wrapper around the MongoDB.Driver; it brings the elegance of ORM-like patterns and the robustness of .NET Core’s architecture together, making it an invaluable asset for any .NET developer working with MongoDB. Give MongoGogo a try in your next project, and experience the benefits of a type-safe, structured, and efficient way to manage your MongoDB databases.

--

--