Installing MongoDB on Windows.
Download MongoDB from its download page, and install it. I chose to install in C:\opt\MongoDB\Server\3.2.
Create a folder for database and a folder for logs. Then create a mongod.cfg to represent this data.
In my case, I put all under a new C:\data\ directory.
c:/data/
db/
logs/
mongod.cfg
And this is the content of mongod.cfg
systemLog:
destination: file
path: c:\data\log\mongod.log
storage:
dbPath: c:\data\db
Install MongoDB as service
Open the command prompt with administrative privileges, and type:
"C:\opt\MongoDB\Server\3.2\bin\mongod.exe" --config "C:\data\mongod.cfg" --install
Verify mongodb is installed. Open command prompt with Win + R, then type services.msc
If you see MongoDB in the list, it is installed as service
Start and Stop and Admin DB
If you installed MongoDB as a service, to start and stop, you need to open the command prompt as admin:
net start MongoDB
net stop MongoDB
Otherwise, you start MongoDB via command line.
"C:\opt\MongoDB\Server\3.2\bin\mongod.exe" --config "C:\data\mongod.cfg"
In this case, to stop, you need to launch the mongo shell
>"C:\opt\MongoDB\Server\3.2\bin\mongo.exe"
And stop the server with the below commands:
MongoDB shell version: 3.2.10
> use admin
> db.shutdownServer()
Admin MongoDB
When MongoDB is running, you can manage it using the mongo
Shell. Go to the mongodb install dir, in my case C:\opt\MongoDB\Server\3.2\, and type:
.\bin\mongo
From the shell, you can manage your dbs. Now, we create a new database and insert new data.
> use myNewDatabase
switched to db myNewDatabase
> db.myCollection.insert({myData:1});
WriteResult({ "nInserted" : 1 })
Test NodeJS app with MongoDB
Now we use mongodb in a test NodeJS application.
to run the application, you need to install mongodb and assert modules, either via npm install <module>
or via package.json
addition and installation .
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
var assert = require('assert');
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/myNewDatabase';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// do some work here with the database.☺
//Close connection
db.close();
}
});
Congratulations, you just connected to your new MongoDB database.
0 Comments