I am using the .NET MongoDb driver and Azure Cosmos DB Emulator. I am trying to create a database and collection on startup of a dotnet core Web Api project.
I am running the following code within the ConfigureServices
function in Startup.cs
.
var connectionString = databaseConfig.GetValue<string>("connectionString");
var databaseName = databaseConfig.GetValue<string>("name");
var client = new MongoClient(connectionString);
var db = client.GetDatabase(databaseName);
var collection = db.GetCollection("users");
This is neither creating the database or the collection. I am viewing this in the emulator's data explorer and Robo3T client.
I was under the impression that client.GetDatabase(databaseName)
and db.GetCollection<User>("users")
will create if the database and collection does not exist respectively.
I can get it to create the database and collection with the following db.CreateCollection("users")
. This will require me to check if the collection first exists and isn't the prescribed approach.
Does anyone have any insights into this behaviour?
Thanks.