First of all to ensure that the correct installation of mongodb, Installation Reference: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian-or-Ubuntu-linux
Then download the mongodb driver of nodejs
Npm install mongodb
Compile a test program:
Var mongodb = require ('mongodb ');
Var server = new mongodb. Server ('localhost', 27017, {auto_reconnect: true });
Var db = new mongodb. Db ('mydb', server, {safe: true });
Db. open (function (err, db ){
If (! Err)
{
Console. log ('connect ');
} Else {
Console. log (err );
}
});
If "connect" is displayed, the connection is successful.
Operations on collection of mongodb
There are two methods to link collection:
Db. collection ('mycoll ', function (err, coll ){});
Db. createCollection ('mycoll ', function (err, coll ){});
The two methods have the second optional parameter {safe: true}. this parameter is used for the first method. If this parameter is added, an error is returned when the collection does not exist, for the second method, an error is reported when the collection exists.
Example:
Var mongodb = require ('mongodb ');
Var server = new mongodb. Server ('localhost', 27017, {auto_reconnect: true });
Var db = new mongodb. Db ('mydb', server, {safe: true });
Db. open (function (err, db ){
If (! Err)
{
Console. log ('connect ');
Db. collection ('mycoll ', {safe: true}, function (err, collection ){
If (err ){
Console. log (err );
}
});
} Else {
Console. log (err );
}
});
Result:
Example:
Var mongodb = require ('mongodb ');
Var server = new mongodb. Server ('localhost', 27017, {auto_reconnect: true });
Var db = new mongodb. Db ('mydb', server, {safe: true });
Db. open (function (err, db ){
If (! Err)
{
Console. log ('connect ');
Db. createCollection ('mycoll ', {safe: true}, function (err, collection ){
If (err ){
Console. log (err );
}
});
} Else {
Console. log (err );
}
});
Result:
To delete a collection, use the dropCollection function:
Example:
Var mongodb = require ('mongodb ');
Var server = new mongodb. Server ('localhost', 27017, {auto_reconnect: true });
Var db = new mongodb. Db ('mydb', server, {safe: true });
Db. open (function (err, db ){
If (! Err)
{
Console. log ('connect ');
Db. dropCollection ('mycoll ', {safe: true}, function (err, result ){
Console. log (result );
});
} Else {
Console. log (err );
}
});
Result:
Add, delete, modify, and query collections