Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core + MongoDB how to create database dynamically

I have a .net core project with MongoDB.

Before starting to work with this I need to create DB for this manually.

I mean I need to go mongo shell and use next commands like this:

use admin
db.createUser(
  {
    user: "admin",
    pwd: "abc123!",
    roles: [ { role: "root", db: "admin" } ]
  }
);
exit;

But I don't like do this every time when I need to deploy my project.

How can I automate this process and creating DB dynamically from C# code or use some other solution if it's possible?

P.S. I use this article for building work with MongoDB + .net core.

like image 851
Taras Kovalenko Avatar asked Aug 19 '26 13:08

Taras Kovalenko


1 Answers

The solution is to use a mongoDb driver. U can get it via nuget.

In general u just instantiate a server object and call GetDatabase to create a Database.

server.GetDatabase("myDB");

This way you can also create users using the mongoDb driver as mentioned here : How to create a user in MongoDB

Further reading:

https://www.nuget.org/packages/MongoDB.Driver/2.3.0

http://mongodb.github.io/mongo-csharp-driver/2.2/getting_started/installation/

The following Video provides a short tutorial how to do it: https://www.youtube.com/watch?v=6x0-vHHHpv8 Thanks to that answer : https://stackoverflow.com/a/30629593/4992212

like image 98
Tobias Theel Avatar answered Aug 21 '26 04:08

Tobias Theel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!