Creates a new Db instance
Name | Type | Default | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
databaseName |
string |
The name of the database this instance represents. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
topology |
Server | ReplSet | Mongos |
The server topology for the database. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
object | null |
optional
Optional settings.
|
Properties:
Name | Type | Description |
---|---|---|
serverConfig |
Server | ReplSet | Mongos | Get the current db topology. |
bufferMaxEntries |
number | Current bufferMaxEntries value for the database |
databaseName |
string | The name of the database this instance represents. |
options |
object | The options associated with the db instance. |
native_parser |
boolean | The current value of the parameter native_parser. |
slaveOk |
boolean | The current slaveOk value for the db instance. |
writeConcern |
object | The current write concern values. |
Fires:
- Db#event:close
- Db#event:authenticated
- Db#event:reconnect
- Db#event:error
- Db#event:timeout
- Db#event:parseError
- Db#event:fullsetup
Returns:
Db instance.Methods
-
Add a user to the database.
Name Type Default Description username
string The username.
password
string The password.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
customData
object null optional Custom data associated with the user (only Mongodb 2.6 or higher)
roles
Array.<object> null optional Roles associated with the created user (only Mongodb 2.6 or higher)
callback
Db~resultCallback The command result callback
Example
// An example of adding a user to the database. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Add a user to the database db.addUser('user', 'name', function(err, result) { test.equal(null, err); // Remove the user from the db db.removeUser('user', function(err, result) { test.equal(null, err); db.close(); }); }); });
-
Return the Admin db instance
Returns:
the new Admin db instance
Example
// Example showing how to access the Admin database for admin level operations. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Use the admin database for the operation var adminDb = db.admin() test.ok(adminDb != null); db.close(); });
-
Authenticate a user against the server.
Name Type Default Description username
string The username.
password
string optional The password.
options
object null optional Optional settings.
Name Type Default Description authMechanism
string MONGODB-CR optional The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN
callback
Db~resultCallback The command result callback
Example
// An example of using the authenticate command. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Add a user to the database db.addUser('user2', 'name', function(err, result) { test.equal(null, err); // Authenticate db.authenticate('user2', 'name', function(err, result) { test.equal(true, result); // Remove the user from the db db.removeUser('user2', function(err, result) { test.equal(null, err); db.close(); }); }); }); });
-
Close the db and it's underlying connections
Name Type Description force
boolean Force close, emitting no events
callback
Db~noResultCallback The result callback
Examples
// An example that shows how to force close a db connection so it cannot be reused. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch a collection var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb'); // Insert a document collection.insert({a:1}, {w:1}, function(err, result) { test.equal(null, err); // Force close the connection db.close(true, function(err, result) { // Attemp to insert should fail now with correct message 'db closed by application' collection.insert({a:2}, {w:1}, function(err, result) { test.equal('db closed by application', err.message); db.close(); }); }); }); });
// An example of a simple single server db connection and close function var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Close the connection with a callback that is optional db.close(function(err, result) { test.equal(null, err); }); });
-
collection(name, options, callback){Collection}
-
Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can can use it without a callback in the following way. var collection = db.collection('mycollection');
Name Type Default Description name
string the collection name we wish to access.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
raw
boolean false optional Return document results as raw BSON buffers.
pkFactory
object null optional A primary key factory object for generation of custom _id keys.
readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
serializeFunctions
boolean false optional Serialize functions on any object.
strict
boolean false optional Returns an error if the collection does not exist
callback
Db~collectionResultCallback The collection result callback
Returns:
the new Collection instance if not in strict mode
Example
// An example of retrieving a collection from a db using the collection function. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Grab a collection without a callback no safe mode var col1 = db.collection('test_correctly_access_collections'); // Grab a collection with a callback but no safe operation db.collection('test_correctly_access_collections', function(err, col2) { test.equal(null, err); // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created) db.collection('test_correctly_access_collections', {strict:true}, function(err, col3) { test.ok(err != null); // Create the collection db.createCollection('test_correctly_access_collections', function(err, result) { // Retry to get the collection, should work as it's now created db.collection('test_correctly_access_collections', {strict:true}, function(err, col3) { test.equal(null, err); db.close(); }); }); }); }); });
-
Fetch all collections for the current db.
Name Type Description callback
Db~collectionsResultCallback optional The results callback
Example
// An example of retrieving all collections for a db as Collection objects var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Create the collection var collection = db.collection('test_correctly_access_collections2'); // Retry to get the collection, should work as it's now created db.collections(function(err, collections) { test.equal(null, err); test.ok(collections.length > 0); db.close(); }); });
-
Execute a command
Name Type Default Description command
object The command hash
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxTimeMS
number null optional Number of milliseconds to wait before aborting the query.
callback
Db~resultCallback The command result callback
Example
// A simple example creating, dropping a collection and then verifying that the collection is gone. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Execute ping against the server db.command({ping:1}, function(err, result) { test.equal(null, err); db.close(); }); });
-
Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
Name Type Default Description name
string the collection name we wish to access.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
raw
boolean false optional Return document results as raw BSON buffers.
pkFactory
object null optional A primary key factory object for generation of custom _id keys.
readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
serializeFunctions
boolean false optional Serialize functions on any object.
strict
boolean false optional Returns an error if the collection does not exist
capped
boolean false optional Create a capped collection.
size
number null optional The size of the capped collection in bytes.
max
number null optional The maximum number of documents in the capped collection.
autoIndexId
boolean true optional Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.
callback
Db~collectionResultCallback The results callback
Example
// A simple example showing the creation of a collection. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Create a capped collection with a maximum of 1000 documents db.createCollection("a_simple_collection", {capped:true, size:10000, max:1000, w:1}, function(err, collection) { test.equal(null, err); // Insert a document in the capped collection collection.insert({a:1}, {w:1}, function(err, result) { test.equal(null, err); db.close(); }); }); });
-
Creates an index on the db and collection collection.
Name Type Default Description name
string Name of the collection to create the index on.
fieldOrSpec
string | object Defines the index.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
unique
boolean false optional Creates an unique index.
sparse
boolean false optional Creates a sparse index.
background
boolean false optional Creates the index in the background, yielding whenever possible.
dropDups
boolean false optional A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
min
number null optional For geospatial indexes set the lower bound for the co-ordinates.
max
number null optional For geospatial indexes set the high bound for the co-ordinates.
v
number null optional Specify the format version of the indexes.
expireAfterSeconds
number null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
number null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
callback
Db~resultCallback The command result callback
Example
// A more complex createIndex using a compound unique index in the background and dropping duplicated documents var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('more_complex_index_test'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field db.createIndex('more_complex_index_test', {a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
-
Create a new Db instance sharing the current socket connections.
Name Type Description name
string The name of the database we want to use.
Example
// Simple example connecting to two different databases sharing the socket connections below. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Reference a different database sharing the same connections // for the data transfer var secondDb = db.db("integration_tests_2"); // Fetch the collections var multipleColl1 = db.collection("multiple_db_instances"); var multipleColl2 = secondDb.collection("multiple_db_instances"); // Write a record into each and then count the records stored multipleColl1.insert({a:1}, {w:1}, function(err, result) { multipleColl2.insert({a:1}, {w:1}, function(err, result) { // Count over the results ensuring only on record in each collection multipleColl1.count(function(err, count) { test.equal(1, count); multipleColl2.count(function(err, count) { test.equal(1, count); db.close(); }); }); }); }); });
-
Drop a collection from the database, removing it permanently. New accesses will create a new collection.
Name Type Description name
string Name of collection to drop
callback
Db~resultCallback The results callback
Example
// A simple example executing a command against the server. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Execute ping against the server db.command({ping:1}, function(err, result) { test.equal(null, err); // Create a capped collection with a maximum of 1000 documents db.createCollection("a_simple_create_drop_collection", {capped:true, size:10000, max:1000, w:1}, function(err, collection) { test.equal(null, err); // Insert a document in the capped collection collection.insert({a:1}, {w:1}, function(err, result) { test.equal(null, err); // Drop the collection from this world db.dropCollection("a_simple_create_drop_collection", function(err, result) { test.equal(null, err); // Verify that the collection is gone db.listCollections("a_simple_create_drop_collection", function(err, names) { test.equal(0, names.length); db.close(); }); }); }); }); }); });
-
Drop a database.
Name Type Description callback
Db~resultCallback optional The results callback
Example
// An examples showing the dropping of a database var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection var collection = db.collection('more_index_information_test_1'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1}, {a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Let's drop the database db.dropDatabase(function(err, result) { test.equal(null, err); // Wait to seconds to let it replicate across setTimeout(function() { // Get the admin database db.admin().listDatabases(function(err, dbs) { // Grab the databases dbs = dbs.databases; // Did we find the db var found = false; // Check if we have the db in the list for(var i = 0; i < dbs.length; i++) { if(dbs[i].name == 'integration_tests_to_drop') found = true; } // We should not find the databases if(process.env['JENKINS'] == null) test.equal(false, found); db.close(); }); }, 2000); }); }); });
-
Ensures that an index exists, if it does not it creates it
Name Type Default Description name
string The index name
fieldOrSpec
string | object Defines the index.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
unique
boolean false optional Creates an unique index.
sparse
boolean false optional Creates a sparse index.
background
boolean false optional Creates the index in the background, yielding whenever possible.
dropDups
boolean false optional A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
min
number null optional For geospatial indexes set the lower bound for the co-ordinates.
max
number null optional For geospatial indexes set the high bound for the co-ordinates.
v
number null optional Specify the format version of the indexes.
expireAfterSeconds
number null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
number null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
callback
Db~resultCallback The command result callback
Example
// A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('more_complex_ensure_index_db_test'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field db.ensureIndex('more_complex_ensure_index_db_test', {a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
-
Evaluate JavaScript on the server
Name Type Default Description code
Code JavaScript to execute on server.
parameters
object | array The parameters for the call.
options
object null optional Optional settings.
Name Type Default Description nolock
boolean false optional Tell MongoDB not to block on the evaulation of the javascript.
callback
Db~resultCallback The results callback
Examples
// A whole bunch of examples on how to use eval on the server. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var numberOfTests = 10; var tests_done = function() { numberOfTests = numberOfTests - 1; if(numberOfTests == 0) { db.close(); } } // Evaluate a function on the server with the parameter 3 passed in db.eval('function (x) {return x;}', [3], function(err, result) { test.equal(3, result); tests_done(); // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval // on server db.eval('function (x) {return x;}', [3], {nolock:true}, function(err, result) { test.equal(3, result); tests_done(); }); // Evaluate a function on the server that writes to a server collection db.eval('function (x) {db.test_eval.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY}, function(err, result) { setTimeout(function() { // Locate the entry db.collection('test_eval', function(err, collection) { collection.findOne(function(err, item) { test.equal(5, item.y); tests_done(); // Evaluate a function with 2 parameters passed in db.eval('function (x, y) {return x + y;}', [2, 3], function(err, result) { test.equal(5, result); tests_done(); // Evaluate a function with no parameters passed in db.eval('function () {return 5;}', function(err, result) { test.equal(5, result); tests_done(); // Evaluate a statement db.eval('2 + 3;', function(err, result) { test.equal(5, result); tests_done(); // Evaluate a statement using the code object db.eval(new Code("2 + 3;"), function(err, result) { test.equal(5, result); tests_done(); // Evaluate a statement using the code object including a scope db.eval(new Code("return i;", {'i':2}), function(err, result) { test.equal(2, result); tests_done(); // Evaluate a statement using the code object including a scope db.eval(new Code("i + 3;", {'i':2}), function(err, result) { test.equal(5, result); tests_done(); // Evaluate an illegal statement db.eval("5 ++ 5;", function(err, result) { test.ok(err instanceof Error); test.ok(err.message != null); tests_done(); // Let's close the db // db.close(); }); }); }); }); }); }); }); }); }); }, 1000); }); }); });
// Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Clean out the collection db.collection("system.js").remove({}, {w:1}, function(err, result) { test.equal(null, err); // Define a system level function db.collection("system.js").insert({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}, function(err, result) { test.equal(null, err); db.eval("echo(5)", function(err, result) { test.equal(null, err); test.equal(5, result); db.close(); }); }); }); });
-
Runs a command on the database as admin.
Name Type Default Description command
object The command hash
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxTimeMS
number null optional Number of milliseconds to wait before aborting the query.
callback
Db~resultCallback The command result callback
-
Retrieves this collections index info.
Name Type Default Description name
string The name of the collection.
options
object null optional Optional settings.
Name Type Default Description full
boolean false optional Returns the full raw index information.
readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callback
Db~resultCallback The command result callback
-
Get the list of all collection information for the specified db.
Name Type Default Description name
string null optional Filter by a specific collection name.
options
object null optional Optional settings.
Name Type Default Description filter
string | object null optional Filter collections by this filter (string or object)
namesOnly
boolean false optional Return only the full collection namespace.
callback
Db~resultCallback The results callback
Examples
// An example of retrieving the collections list for a database. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Create a collection var collection = db.collection('test_collections_info'); // Return the information of a single collection name db.listCollections("test_collections_info", function(err, items) { test.equal(1, items.length); // Return the information of a all collections, using the callback format db.listCollections(function(err, items) { test.ok(items.length > 0); db.close(); }); }); });
// An example of retrieving the collection names for a database using a filter var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Create a collection var collection = db.collection('test_collections_info2'); collection.insert({a:1}, function(err, r) { test.equal(null, err); // Return the information of a single collection name db.listCollections({ filter: { name: /test_collections_info2/ }}, function(err, items) { test.equal(1, items.length); // Return the information of a all collections, using the callback format db.listCollections(function(err, items) { test.ok(items.length > 0); db.close(); }); }); }); });
-
Logout user from server, fire off on all connections and remove all auth info
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description dbName
string null optional Logout against different database than current.
callback
Db~resultCallback The command result callback
Example
// An example of using the logout command for the database. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Add a user to the database db.addUser('user3', 'name', function(err, result) { test.equal(null, err); // Authenticate db.authenticate('user3', 'name', function(err, result) { test.equal(true, result); // Logout the db db.logout(function(err, result) { test.equal(true, result); // Remove the user db.removeUser('user3', function(err, result) { test.equal(true, result); db.close(); }); }); }); }); });
-
Open the database
Name Type Description callback
Db~openCallback Callback
Examples
// An example of a simple single server db connection var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); db.on('close', function() { }) db.close(); });
// Simple replicaset connection setup, requires a running replicaset on the correct ports var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); p_db.close(); });
-
Remove a user from a database
Name Type Default Description username
string The username.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Db~resultCallback The command result callback
Example
// An example of dereferencing values. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Add a user to the database db.addUser('user', 'name', function(err, result) { test.equal(null, err); // Authenticate db.authenticate('user', 'name', function(err, result) { test.equal(true, result); // Logout the db db.logout(function(err, result) { test.equal(true, result); // Remove the user from the db db.removeUser('user', function(err, result) { // Authenticate db.authenticate('user', 'name', function(err, result) { test.equal(false, result); db.close(); }); }); }); }); }); });
-
Rename a collection.
Name Type Default Description fromCollection
string Name of current collection to rename.
toCollection
string New name of of the collection.
options
object null optional Optional settings.
Name Type Default Description dropTarget
boolean false optional Drop the target name collection if it previously exists.
callback
Db~collectionResultCallback The results callback
Example
// A simple example creating, dropping a collection and then verifying that the collection is gone. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Create a collection db.createCollection("simple_rename_collection", {w:1}, function(err, collection) { test.equal(null, err); // Insert a document in the collection collection.insert({a:1}, {w:1}, function(err, result) { test.equal(null, err); // Retrieve the number of documents from the collection collection.count(function(err, count) { test.equal(1, count); // Rename the collection db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) { test.equal(null, err); // Retrieve the number of documents from the collection collection2.count(function(err, count) { test.equal(1, count); // Verify that the collection is gone db.listCollections("simple_rename_collection", function(err, names) { test.equal(0, names.length); // Verify that the new collection exists db.listCollections("simple_rename_collection_2", function(err, names) { test.equal(1, names.length); db.close(); }); }); }); }); }); }); }); });
-
Get all the db statistics.
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description scale
number null optional Divide the returned sizes by scale value.
callback
Db~resultCallback The collection result callback
Example
// An example showing how to retrieve the db statistics var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); db.stats(function(err, stats) { test.equal(null, err); test.ok(stats != null); db.close(); }) });
Type Definitions
-
The callback format for the collection method, must be used if strict is specified
Name Type Description error
MongoError An error instance representing the error during the execution.
collection
Collection The collection instance.
-
The callback format for the collections method.
Name Type Description error
MongoError An error instance representing the error during the execution.
collections
Array.<Collection> An array of all the collections objects for the db instance.
-
The callback format for results
Name Type Description error
MongoError An error instance representing the error during the execution.
result
null Is not set to a value
-
The callback format for the Db.open method
Name Type Description error
MongoError An error instance representing the error during the execution.
db
Db The Db instance if the open method was successful.
-
The callback format for results
Name Type Description error
MongoError An error instance representing the error during the execution.
result
object The result object if the command was executed successfully.
Events
-
Db authenticated event
Type:
- object
-
Db close event
Type:
- object
-
Db error event
Type:
- MongoError
-
Db fullsetup event, emitted when all servers in the topology have been connected to.
Type:
-
Db parseError event
Type:
- object
-
Db reconnect event
Type:
- object
-
Db timeout event
Type:
- object