MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

How to create a database programmatically

Hello.
Would be possible to create a database programmatically using the c# driver, if not possible then to run a shell command via c#.
I like to create a database per use and don’t have many users, just that it is only known at runtime.
Any examples would be grateful.
Thanks.

MongoDB creates databases and collections on first write. This means they don’t need to be precreated. MongoDB will allow you to connect to a database that doesn’t exist. Because of this, you should be able to make the connection with the new database name and then send a write command to it and the database and collection will get created.

1 Like

Thank you Doug. Yes, learnt that the hard way.
Would be nice if that existed in the c# driver manual.

1 Like

Don’t forget to create the indexes as well if you’re scripting the database, it’s fairly straight forward to do in the C# driver but let me know if you want some help with it, below are a couple of examples:

An index on two fields

          var index = new CreateIndexModel<T>(
                Builders<T>
                    .IndexKeys
                    .Descending(i => i.Feild1)
                    .Descending(i => i.Feild2)
            );

A Time to Live index (lasting 21 hours), object T will need to have a DateTime property…

var ttlIndex = new CreateIndexModel<T>(
                Builders<T>
                    .IndexKeys
                    .Ascending(i => i.DateTime),
                new CreateIndexOptions { ExpireAfter = TimeSpan.FromHours(21) }
            );
1 Like