1

I have created an ASP.NET MVC 5 application, and I am hosting it on IIS 7. I would now like to start using a MongoDB database with this application. I have managed to get a MongoDB Windows Service running, but I am now stuck as to what the next step is.

Namely:

i) How do I specify in my ASP.NET MVC application what the name of the database is, and the directory where it is stored?

ii) How do I create this database in MongoDB?

In my Web.config file, I have the following lines:

<connectionStrings>
    <add name="Mongo" connectionString="mongodb://localhost" />
</connectionStrings>

and:

<appSettings>
    <add key="DbName" value="mydb" />
    <add key="MONGOHQ_URL" value="mongodb://localhost" />
</appSettings>

So how do I now go about creating a database called mydb such that it is running in the MongoDB Windows Service?

1 Answer 1

2

i) How do I specify in my ASP.NET MVC application what the name of the database is, and the directory where it is stored?

The directory where it is stored is specified by your mongod instance, not your MVC application. When you start your mongod instance, you should have something like:

mongod.exe --dbpath [where your db is stored]

To know more about mongod.exe parameters, have a look at here.
The name of your database is specified in the connection string. It would be something like:

mongodb://localhost/dbName?[options]

You can find the whole instruction here.
However, I don't know if I'm the only one who finds the C# driver API sort of tricky. To initialize a MongoClient (top level database object), most people would go with the most simple way:

MongoClient client = new MongoClient(connStr);

This way you'll never get the database name. To get it:

MongoUrl url = new MongoUrl(connStr);
MongoClient client = new MongoClient(url);
var dbName = url.DatabaseName  // retrive database name
var db = client.GetServer().GetDatabase(dbName);

This way you can store database name with connection string. Which seems to be good to me. But you can of course use another appSetting to store the db name.

ii) How do I create this database in MongoDB?

You don't have to. When you insert data into the database for the first time, mongod will create database for you, as well as collections. Although later on you may find it useful to build indexes on some of the collections.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.