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. |
topology |
object | Access the topology object (single server, replicaset or mongos). |
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 usernamestring The username.
passwordstring The password.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
customDataobject null optional Custom data associated with the user (only Mongodb 2.6 or higher)
rolesArray.<object> null optional Roles associated with the created user (only Mongodb 2.6 or higher)
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
Examples
// 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(); }); }); });// An example of adding a user to the database using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Add a user to the database db.addUser('user', 'name').then(function(result) { // Remove the user from the db db.removeUser('user').then(function(result) { db.close(); }); }); });// An example of adding a user to the database using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Add a user to the database yield db.addUser('user', 'name'); // Remove the user from the db yield db.removeUser('user'); 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 usernamestring The username.
passwordstring optional The password.
optionsobject null optional Optional settings.
Name Type Default Description authMechanismstring MONGODB-CR optional The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN
callbackDb~resultCallback optional The command result callback
- Deprecated
- This method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Returns:
Promise if no callback passed
Examples
// 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(); }); }); }); });// An example of using the authenticate command with a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Add a user to the database db.addUser('user2', 'name').then(function(result) { // Authenticate db.authenticate('user2', 'name').then(function(result) { test.equal(true, result); // Remove the user from the db db.removeUser('user2').then(function(result) { db.close(); }); }); }); });// An example of using the authenticate command with a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Add a user to the database yield db.addUser('user2', 'name'); // Authenticate var result = yield db.authenticate('user2', 'name'); test.equal(true, result); // Remove the user from the db yield db.removeUser('user2'); db.close(); }); -
Close the db and its underlying connections
Name Type Description forceboolean Force close, emitting no events
callbackDb~noResultCallback optional The result callback
Returns:
Promise if no callback passed
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.insertOne({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.insertOne({a:2}, {w:1}, function(err, result) { test.ok(err != null); 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); }); });// An example that shows how to force close a db connection so it cannot be reused using a Promise.. 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_with_promise'); // Insert a document collection.insertOne({a:1}, {w:1}).then(function(result) { // Force close the connection db.close(true).then(function() { // Attemp to insert should fail now with correct message 'db closed by application' collection.insertOne({a:2}, {w:1}).then(function(result) { }).catch(function(err) { db.close(); }); }); }); });// An example of a simple single server db connection and close function using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Close the connection with a callback that is optional db.close().then(function(result) { }); });// An example that shows how to force close a db connection so it cannot be reused using a Generator and the co module.. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Fetch a collection var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb_with_generators'); // Insert a document yield collection.insertOne({a:1}, {w:1}); // Force close the connection yield db.close(true) try { // Attemp to insert should fail now with correct message 'db closed by application' yield collection.insertOne({a:2}, {w:1}); } catch(err) { db.close(); } }); -
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 namestring the collection name we wish to access.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
rawboolean false optional Return document results as raw BSON buffers.
pkFactoryobject null optional A primary key factory object for generation of custom _id keys.
readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
serializeFunctionsboolean false optional Serialize functions on any object.
strictboolean false optional Returns an error if the collection does not exist
readConcernobject null optional Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
Name Type Default Description levelobject 'local' optional Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
callbackDb~collectionResultCallback The collection result callback
Returns:
the new Collection instance if not in strict mode
Examples
// 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(); }); }); }); }); });// An example of retrieving a collection from a db using the collection function with a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Grab a collection without a callback no safe mode var col1 = db.collection('test_correctly_access_collections_with_promise'); // Grab a collection with a callback but no safe operation db.collection('test_correctly_access_collections_with_promise', function(err, col2) { // 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_with_promise', {strict:true}, function(err, col3) { // Create the collection db.createCollection('test_correctly_access_collections_with_promise').then(function(err, result) { // Retry to get the collection, should work as it's now created db.collection('test_correctly_access_collections_with_promise', {strict:true}, function(err, col3) { db.close(); }); }); }); }); }); -
Fetch all collections for the current db.
Name Type Description callbackDb~collectionsResultCallback optional The results callback
Returns:
Promise if no callback passed
Examples
// 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(); }); });// An example of retrieving all collections for a db as Collection objects using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create the collection var collection = db.collection('test_correctly_access_collections2_with_promise'); // Retry to get the collection, should work as it's now created db.collections().then(function(collections) { test.ok(collections.length > 0); db.close(); }); });// An example of retrieving all collections for a db as Collection objects using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create the collection var collection = db.collection('test_correctly_access_collections2_with_generators'); // Retry to get the collection, should work as it's now created var collections = yield db.collections(); test.ok(collections.length > 0); db.close(); }); -
Execute a command
Name Type Default Description commandobject The command hash
optionsobject null optional Optional settings.
Name Type Default Description readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
Examples
// 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); db.close(); }); });// A simple example executing a command against the server using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Execute ping against the server db.command({ping:1}).then(function(result) { db.close(); }); });// A simple example executing a command against the server using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Execute ping against the server yield db.command({ping:1}); db.close(); }); -
Create a new collection on a server with the specified options. Use this to create capped collections.
More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/Name Type Default Description namestring the collection name we wish to access.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
rawboolean false optional Return document results as raw BSON buffers.
pkFactoryobject null optional A primary key factory object for generation of custom _id keys.
readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
serializeFunctionsboolean false optional Serialize functions on any object.
strictboolean false optional Returns an error if the collection does not exist
cappedboolean false optional Create a capped collection.
autoIndexIdboolean 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.
sizenumber null optional The size of the capped collection in bytes.
maxnumber null optional The maximum number of documents in the capped collection.
flagsnumber null optional Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.
storageEngineobject null optional Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.
validatorobject null optional Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.
validationLevelstring null optional Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.
validationActionstring null optional Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.
indexOptionDefaultsobject null optional Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.
viewOnstring null optional The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.
pipelinearray null optional An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.
collationobject null optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
callbackDb~collectionResultCallback optional The results callback
Returns:
Promise if no callback passed
Examples
// 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.insertOne({a:1}, {w:1}, function(err, result) { test.equal(null, err); db.close(); }); }); });// A simple example showing the listening to a capped 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_2", {capped:true, size:100000, max:10000, w:1}, function(err, collection) { test.equal(null, err); var docs = []; for(var i = 0; i < 1000; i++) docs.push({a:i}); // Insert a document in the capped collection collection.insertMany(docs, {w:1}, function(err, result) { // Start date var s = new Date(); var total = 0; // Get the cursor var cursor = collection.find({}) .addCursorFlag('tailable', true) .addCursorFlag('awaitData', true); cursor.on('data', function() { total = total + 1; if(total == 1000) { cursor.kill(); } }); cursor.on('end', function() { db.close(); }); }); }); });// A simple example showing the creation of a collection using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a capped collection with a maximum of 1000 documents db.createCollection("a_simple_collection_with_promise", {capped:true, size:10000, max:1000, w:1}).then(function(collection) { // Insert a document in the capped collection collection.insertOne({a:1}, {w:1}).then(function(result) { db.close(); }); }); });// A simple example showing the listening to a capped collection using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a capped collection with a maximum of 1000 documents db.createCollection("a_simple_collection_2_with_promise", {capped:true, size:100000, max:10000, w:1}).then(function(collection) { var docs = []; for(var i = 0; i < 1000; i++) docs.push({a:i}); // Insert a document in the capped collection collection.insertMany(docs, {w:1}).then(function(result) { // Start date var s = new Date(); var total = 0; // Get the cursor var cursor = collection.find({a: {$gte:0}}) .addCursorFlag('tailable', true) .addCursorFlag('awaitData', true) cursor.on('data', function(d) { total = total + 1; if(total == 1000) { cursor.kill(); } }); cursor.on('end', function() { console.dir(new Date().getTime() - s.getTime()) test.ok((new Date().getTime() - s.getTime()) > 1000); db.close(); }); }); }); });// A simple example showing the creation of a collection using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a capped collection with a maximum of 1000 documents var collection = yield db.createCollection("a_simple_collection_with_generators", {capped:true, size:10000, max:1000, w:1}); // Insert a document in the capped collection yield collection.insertOne({a:1}, {w:1}); db.close(); });// A simple example showing the listening to a capped collection using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a capped collection with a maximum of 1000 documents var collection = yield db.createCollection("a_simple_collection_2_with_generators", {capped:true, size:100000, max:10000, w:1}); var docs = []; for(var i = 0; i < 1000; i++) docs.push({a:i}); // Insert a document in the capped collection yield collection.insertMany(docs, {w:1}); // Start date var s = new Date(); var total = 0; // Get the cursor var cursor = collection.find({}) .addCursorFlag('tailable', true) .addCursorFlag('awaitData', true) cursor.on('data', function() { total = total + 1; if(total == 1000) { cursor.kill(); } }); cursor.on('end', function() { db.close(); }); }); -
Creates an index on the db and collection collection.
Name Type Default Description namestring Name of the collection to create the index on.
fieldOrSpecstring | object Defines the index.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
uniqueboolean false optional Creates an unique index.
sparseboolean false optional Creates a sparse index.
backgroundboolean false optional Creates the index in the background, yielding whenever possible.
dropDupsboolean 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
minnumber null optional For geospatial indexes set the lower bound for the co-ordinates.
maxnumber null optional For geospatial indexes set the high bound for the co-ordinates.
vnumber null optional Specify the format version of the indexes.
expireAfterSecondsnumber null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
namenumber null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
partialFilterExpressionobject null optional Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
Examples
// 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.insertMany([{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); // Perform a query, with explain to show we hit the query collection.find({a:2}).explain(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });// A more complex createIndex using a compound unique index in the background and dropping duplicated documents using a Promise. 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_with_promise'); // Insert a bunch of documents for the index collection.insertMany([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) { // Create an index on the a field db.createIndex('more_complex_index_test_with_promise', {a:1, b:1} , {unique:true, background:true, w:1}).then(function(indexName) { // Show that duplicate records got dropped collection.find({}).toArray().then(function(items) { test.equal(4, items.length); // Perform a query, with explain to show we hit the query collection.find({a:2}).explain().then(function(explanation) { test.ok(explanation != null); db.close(); }); }) }); }); });// A more complex createIndex using a compound unique index in the background and dropping duplicated documents using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a collection we want to drop later var collection = db.collection('more_complex_index_test_with_generators'); // Insert a bunch of documents for the index yield collection.insertMany([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}); // Create an index on the a field yield db.createIndex('more_complex_index_test_with_generators', {a:1, b:1} , {unique:true, background:true, w:1}); // Show that duplicate records got dropped var items = yield collection.find({}).toArray(); test.equal(4, items.length); // Perform a query, with explain to show we hit the query var explanation = yield collection.find({a:2}).explain(); test.ok(explanation != null); db.close(); }); -
Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
related in a parent-child relationship to the original instance so that events are correctly emitted on child
db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
You can control these behaviors with the options noListener and returnNonCachedInstance.Name Type Default Description namestring The name of the database we want to use.
optionsobject null optional Optional settings.
Name Type Default Description noListenerboolean false optional Do not make the db an event listener to the original connection.
returnNonCachedInstanceboolean false optional Control if you want to return a cached instance or have a new one created
Examples
// 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.insertOne({a:1}, {w:1}, function(err, result) { multipleColl2.insertOne({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(); }); }); }); }); });// Simple example connecting to two different databases sharing the socket connections below using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // 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_with_promise"); var multipleColl2 = secondDb.collection("multiple_db_instances_with_promise"); // Write a record into each and then count the records stored multipleColl1.insertOne({a:1}, {w:1}).then(function(result) { multipleColl2.insertOne({a:1}, {w:1}).then(function(result) { // Count over the results ensuring only on record in each collection multipleColl1.count().then(function(count) { test.equal(1, count); multipleColl2.count().then(function(count) { test.equal(1, count); db.close(); }); }); }); }); });// Simple example connecting to two different databases sharing the socket connections below using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // 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_with_generators"); var multipleColl2 = secondDb.collection("multiple_db_instances_with_generators"); // Write a record into each and then count the records stored yield multipleColl1.insertOne({a:1}, {w:1}); yield multipleColl2.insertOne({a:1}, {w:1}) // Count over the results ensuring only on record in each collection var count = yield multipleColl1.count(); test.equal(1, count); var count = yield multipleColl2.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 namestring Name of collection to drop
callbackDb~resultCallback optional The results callback
Returns:
Promise if no callback passed
Examples
// 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); // 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.insertOne({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({name:"a_simple_create_drop_collection"}).toArray(function(err, names) { test.equal(0, names.length); db.close(); }); }); }); }); }); });// A simple example creating, dropping a collection and then verifying that the collection is gone using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Execute ping against the server db.command({ping:1}).then(function(result) { // Create a capped collection with a maximum of 1000 documents db.createCollection("a_simple_create_drop_collection_with_promise", {capped:true, size:10000, max:1000, w:1}).then(function(collection) { // Insert a document in the capped collection collection.insertOne({a:1}, {w:1}).then(function(result) { // Drop the collection from this world db.dropCollection("a_simple_create_drop_collection_with_promise").then(function(result) { // Verify that the collection is gone db.listCollections({name:"a_simple_create_drop_collection_with_promise"}).toArray().then(function(names) { test.equal(0, names.length); db.close(); }); }); }); }); }); });// A simple example creating, dropping a collection and then verifying that the collection is gone using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Execute ping against the server yield db.command({ping:1}); // Create a capped collection with a maximum of 1000 documents var collection = yield db.createCollection("a_simple_create_drop_collection_with_generators", {capped:true, size:10000, max:1000, w:1}); // Insert a document in the capped collection yield collection.insertOne({a:1}, {w:1}); // Drop the collection from this world yield db.dropCollection("a_simple_create_drop_collection_with_generators"); // Verify that the collection is gone var names = yield db.listCollections({name:"a_simple_create_drop_collection_with_generators"}).toArray(); test.equal(0, names.length); db.close(); }); -
Drop a database, removing it permanently from the server.
Name Type Description callbackDb~resultCallback optional The results callback
Returns:
Promise if no callback passed
Examples
// 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.insertMany([{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 two 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); }); }); });// An examples showing the dropping of a database using a Promise. 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_with_promise'); // Insert a bunch of documents for the index collection.insertMany([{a:1, b:1}, {a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) { // Let's drop the database db.dropDatabase().then(function(result) { // Wait two seconds to let it replicate across setTimeout(function() { // Get the admin database db.admin().listDatabases().then(function(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); }); }); });// An examples showing the dropping of a database using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a collection var collection = db.collection('more_index_information_test_1_with_generators'); // Insert a bunch of documents for the index yield collection.insertMany([{a:1, b:1}, {a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}); // Let's drop the database yield db.dropDatabase(); // Wait two seconds to let it replicate across setTimeout(function() { co(function*() { // Get the admin database var dbs = yield db.admin().listDatabases(); // 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 namestring The index name
fieldOrSpecstring | object Defines the index.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
uniqueboolean false optional Creates an unique index.
sparseboolean false optional Creates a sparse index.
backgroundboolean false optional Creates the index in the background, yielding whenever possible.
dropDupsboolean 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
minnumber null optional For geospatial indexes set the lower bound for the co-ordinates.
maxnumber null optional For geospatial indexes set the high bound for the co-ordinates.
vnumber null optional Specify the format version of the indexes.
expireAfterSecondsnumber null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
namenumber null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
callbackDb~resultCallback optional The command result callback
- Deprecated
- since version 2.0
Returns:
Promise if no callback passed
Examples
// 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.insertMany([{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); // Perform a query, with explain to show we hit the query collection.find({a:2}).explain(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });// A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents using a Promise. 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_with_promise'); // Insert a bunch of documents for the index collection.insertMany([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) { // Create an index on the a field db.ensureIndex('more_complex_ensure_index_db_test_with_promise', {a:1, b:1} , {unique:true, background:true, w:1}).then(function(indexName) { // Show that duplicate records got dropped collection.find({}).toArray().then(function(items) { test.equal(4, items.length); // Perform a query, with explain to show we hit the query collection.find({a:2}).explain().then(function(explanation) { test.ok(explanation != null); db.close(); }); }) }); }); });// A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a collection we want to drop later var collection = db.collection('more_complex_ensure_index_db_test_with_generators'); // Insert a bunch of documents for the index yield collection.insertMany([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}); // Create an index on the a field yield db.ensureIndex('more_complex_ensure_index_db_test_with_generators', {a:1, b:1} , {unique:true, background:true, w:1}); // Show that duplicate records got dropped var items = yield collection.find({}).toArray(); test.equal(4, items.length); // Perform a query, with explain to show we hit the query var explanation = yield collection.find({a:2}).explain(); test.ok(explanation != null); db.close(); }); -
Evaluate JavaScript on the server
Name Type Default Description codeCode JavaScript to execute on server.
parametersobject | array The parameters for the call.
optionsobject null optional Optional settings.
Name Type Default Description nolockboolean false optional Tell MongoDB not to block on the evaluation of the javascript.
callbackDb~resultCallback optional The results callback
- Deprecated
- Eval is deprecated on MongoDB 3.2 and forward
Returns:
Promise if no callback passed
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").deleteMany({}, {w:1}, function(err, result) { test.equal(null, err); // Define a system level function db.collection("system.js").insertOne({_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(); }); }); }); });// A whole bunch of examples on how to use eval on the server with a Promise. 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]).then(function(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}).then(function(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_with_promise.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY}).then(function(result) { setTimeout(function() { // Locate the entry db.collection('test_eval_with_promise', function(err, collection) { collection.findOne().then(function(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]).then(function(result) { test.equal(5, result); tests_done(); // Evaluate a function with no parameters passed in db.eval('function () {return 5;}').then(function(result) { test.equal(5, result); tests_done(); // Evaluate a statement db.eval('2 + 3;').then(function(result) { test.equal(5, result); tests_done(); // Evaluate a statement using the code object db.eval(new Code("2 + 3;")).then(function(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})).then(function(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})).then(function(result) { test.equal(5, result); tests_done(); // Evaluate an illegal statement db.eval("5 ++ 5;").then(function(result) { }).catch(function(err) { test.ok(err instanceof Error); test.ok(err.message != null); tests_done(); }); }); }); }); }); }); }); }); }); }, 1000); }); }); });// Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) using a Promise. 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").deleteMany({}, {w:1}).then(function(result) { // Define a system level function db.collection("system.js").insertOne({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}).then(function(result) { db.eval("echo(5)").then(function(result) { test.equal(5, result); db.close(); }); }); }); });// A whole bunch of examples on how to use eval on the server with a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); 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 var result = yield db.eval('function (x) {return x;}', [3]); 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 var result = yield db.eval('function (x) {return x;}', [3], {nolock:true}) test.equal(3, result); tests_done(); // Evaluate a function on the server that writes to a server collection var result = yield db.eval('function (x) {db.test_eval_with_generators.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY}); setTimeout(function() { co(function*() { // Locate the entry var collection = db.collection('test_eval_with_generators'); var item = yield collection.findOne(); test.equal(5, item.y); tests_done(); // Evaluate a function with 2 parameters passed in var result = yield db.eval('function (x, y) {return x + y;}', [2, 3]); test.equal(5, result); tests_done(); // Evaluate a function with no parameters passed in var result = yield db.eval('function () {return 5;}'); test.equal(5, result); tests_done(); // Evaluate a statement var result = yield db.eval('2 + 3;'); test.equal(5, result); tests_done(); // Evaluate a statement using the code object var result = yield db.eval(new Code("2 + 3;")); test.equal(5, result); tests_done(); // Evaluate a statement using the code object including a scope var result = yield db.eval(new Code("return i;", {'i':2})) test.equal(2, result); tests_done(); // Evaluate a statement using the code object including a scope var result = yield db.eval(new Code("i + 3;", {'i':2})); test.equal(5, result); tests_done(); try { // Evaluate an illegal statement yield db.eval("5 ++ 5;"); } catch(err) { test.ok(err instanceof Error); test.ok(err.message != null); tests_done(); } }); }, 1000); });// Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Clean out the collection yield db.collection("system.js").deleteMany({}, {w:1}); // Define a system level function yield db.collection("system.js").insertOne({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}); var result = yield db.eval("echo(5)"); test.equal(5, result); db.close(); }); -
Runs a command on the database as admin.
Name Type Default Description commandobject The command hash
optionsobject null optional Optional settings.
Name Type Default Description readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
Retrieves this collections index info.
Name Type Default Description namestring The name of the collection.
optionsobject null optional Optional settings.
Name Type Default Description fullboolean false optional Returns the full raw index information.
readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
listCollections(filter, options){CommandCursor}
-
Get the list of all collection information for the specified db.
Name Type Default Description filterobject {} optional Query to filter collections by
optionsobject null optional Optional settings.
Name Type Default Description batchSizenumber null optional The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
readPreferenceReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
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); // Get an empty db var db1 = db.db('listCollectionTestDb'); // Create a collection var collection = db1.collection('shouldCorrectlyRetrievelistCollections'); // Ensure the collection was created collection.insertOne({a:1}, function(err, r) { test.equal(null, err); // Return the information of a single collection name db1.listCollections({name: "shouldCorrectlyRetrievelistCollections"}).toArray(function(err, items) { test.equal(1, items.length); // Return the information of a all collections, using the callback format db1.listCollections().toArray(function(err, items) { test.ok(items.length >= 1); db.close(); }); }); }); });// An example of retrieving the collections list for a database using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get an empty db var db1 = db.db('listCollectionTestDb2'); // Create a collection var collection = db1.collection('shouldCorrectlyRetrievelistCollections_with_promise'); // Ensure the collection was created collection.insertOne({a:1}).then(function(r) { // Return the information of a single collection name db1.listCollections({name: "shouldCorrectlyRetrievelistCollections_with_promise"}).toArray().then(function(items) { test.equal(1, items.length); // Return the information of a all collections, using the callback format db1.listCollections().toArray().then(function(items) { test.ok(items.length >= 1); db.close(); }); }).catch(function(err) { console.dir(err) }); }); });// An example of retrieving the collections list for a database using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Get an empty db var db1 = db.db('listCollectionTestDb2Generator'); // Create a collection var collection = db1.collection('shouldCorrectlyRetrievelistCollections_with_generators'); // Ensure the collection was created yield collection.insertOne({a:1}); // Return the information of a single collection name var items = yield db1.listCollections({name: "shouldCorrectlyRetrievelistCollections_with_generators"}).toArray(); test.equal(1, items.length); // Return the information of a all collections, using the callback format var items = yield db1.listCollections().toArray(); test.ok(items.length >= 1); db.close(); }); -
Logout user from server, fire off on all connections and remove all auth info
Name Type Default Description optionsobject null optional Optional settings.
Name Type Default Description dbNamestring null optional Logout against different database than current.
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
Examples
// 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); // console.log("--------- 0") // Logout the db db.logout(function(err, result) { // console.log("---------- 1") // console.dir(result) test.equal(true, result); // Remove the user db.removeUser('user3', function(err, result) { test.equal(true, result); db.close(); }); }); }); }); });// An example of using the logout command for the database with a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Add a user to the database db.addUser('user3', 'name').then(function(result) { // console.log("============================================= 2") // console.dir(result) // Authenticate db.authenticate('user3', 'name').then(function(result) { // console.log("============================================= 3") test.equal(true, result); // Logout the db db.logout().then(function(result) { // console.log("============================================= 4") test.equal(true, result); // Remove the user db.removeUser('user3').then(function(result) { // console.log("============================================= 5") test.equal(true, result); db.close(); }).catch(function(err) { console.dir(err )}) }).catch(function(err) { console.dir(err )}) }).catch(function(err) { console.dir(err )}) }).catch(function(err) { console.dir(err )}) });// An example of using the logout command for the database with a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Add a user to the database var result = yield db.addUser('user3', 'name') // Authenticate var result = yield db.authenticate('user3', 'name'); test.equal(true, result); // Logout the db var result = yield db.logout() test.equal(true, result); // Remove the user var result = yield db.removeUser('user3'); test.equal(true, result); db.close(); }); -
Open the database
Name Type Description callbackDb~openCallback optional Callback
Returns:
Promise if no callback passed
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(); });// Simple replicaset connection setup, requires a running replicaset on the correct ports using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { p_db.close(); }); -
Remove a user from a database
Name Type Default Description usernamestring The username.
optionsobject null optional Optional settings.
Name Type Default Description wnumber | string null optional The write concern.
wtimeoutnumber null optional The write concern timeout.
jboolean false optional Specify a journal write concern.
callbackDb~resultCallback optional The command result callback
Returns:
Promise if no callback passed
Examples
// An example of removing a user. 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(); }); }); }); }); }); });// An example of removing a user using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Add a user to the database db.addUser('user', 'name').then(function(result) { // Authenticate db.authenticate('user', 'name').then(function(result) { test.equal(true, result); // Logout the db db.logout().then(function(result) { test.equal(true, result); // Remove the user from the db db.removeUser('user').then(function(result) { // Authenticate db.authenticate('user', 'name').then(function(result) { test.equal(false, result); db.close(); }).catch(function(err) { db.close(); }); }); }); }); }); });// An example of removing a user using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Add a user to the database yield db.addUser('user', 'name'); // Authenticate var result = yield db.authenticate('user', 'name'); test.equal(true, result); // Logout the db var result = yield db.logout(); test.equal(true, result); // Remove the user from the db yield db.removeUser('user'); try { // Authenticate var result = yield db.authenticate('user', 'name'); assert.ok(false); } catch(err) {} db.close(); }).catch(function(err) { console.log(err.stack) }); -
Rename a collection.
Name Type Default Description fromCollectionstring Name of current collection to rename.
toCollectionstring New name of of the collection.
optionsobject null optional Optional settings.
Name Type Default Description dropTargetboolean false optional Drop the target name collection if it previously exists.
callbackDb~collectionResultCallback optional The results callback
Returns:
Promise if no callback passed
Examples
// 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.insertOne({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({name:"simple_rename_collection"}).toArray(function(err, names) { test.equal(0, names.length); // Verify that the new collection exists db.listCollections({name:"simple_rename_collection_2"}).toArray(function(err, names) { test.equal(1, names.length); db.close(); }); }); }); }); }); }); }); });// 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) { // Create a collection db.createCollection("simple_rename_collection_with_promise", {w:1}).then(function(collection) { // Insert a document in the collection collection.insertOne({a:1}, {w:1}).then(function(result) { // Retrieve the number of documents from the collection collection.count().then(function(count) { test.equal(1, count); // Rename the collection db.renameCollection("simple_rename_collection_with_promise", "simple_rename_collection_2_with_promise").then(function(collection2) { // Retrieve the number of documents from the collection collection2.count().then(function(count) { test.equal(1, count); // Verify that the collection is gone db.listCollections({name:"simple_rename_collection_with_promise"}).toArray().then(function(names) { test.equal(0, names.length); // Verify that the new collection exists db.listCollections({name:"simple_rename_collection_2_with_promise"}).toArray().then(function(names) { test.equal(1, names.length); db.close(); }); }); }); }); }); }); }); });// A simple example creating, dropping a collection and then verifying that the collection is gone. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a collection var collection = yield db.createCollection("simple_rename_collection_with_generators", {w:1}); // Insert a document in the collection yield collection.insertOne({a:1}, {w:1}); // Retrieve the number of documents from the collection var count = yield collection.count(); test.equal(1, count); // Rename the collection var collection2 = yield db.renameCollection("simple_rename_collection_with_generators", "simple_rename_collection_2_with_generators"); // Retrieve the number of documents from the collection var count = yield collection2.count(); test.equal(1, count); // Verify that the collection is gone var names = yield db.listCollections({name:"simple_rename_collection_with_generators"}).toArray(); test.equal(0, names.length); // Verify that the new collection exists var names = yield db.listCollections({name:"simple_rename_collection_2_with_generators"}).toArray(); test.equal(1, names.length); db.close(); }); -
Get all the db statistics.
Name Type Default Description optionsobject null optional Optional settings.
Name Type Default Description scalenumber null optional Divide the returned sizes by scale value.
callbackDb~resultCallback optional The collection result callback
Returns:
Promise if no callback passed
Examples
// 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(); }) });// An example showing how to retrieve the db statistics using a Promise. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { db.stats().then(function(stats) { test.ok(stats != null); db.close(); }) });// An example showing how to retrieve the db statistics using a Generator and the co module. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); var stats = yield db.stats() test.ok(stats != null); db.close(); }); -
Unref all sockets
Type Definitions
-
The callback format for the collection method, must be used if strict is specified
Name Type Description errorMongoError An error instance representing the error during the execution.
collectionCollection The collection instance.
-
The callback format for the collections method.
Name Type Description errorMongoError An error instance representing the error during the execution.
collectionsArray.<Collection> An array of all the collections objects for the db instance.
-
The callback format for results
Name Type Description errorMongoError An error instance representing the error during the execution.
resultnull Is not set to a value
-
The callback format for the Db.open method
Name Type Description errorMongoError An error instance representing the error during the execution.
dbDb The Db instance if the open method was successful.
-
The callback format for results
Name Type Description errorMongoError An error instance representing the error during the execution.
resultobject The result object if the command was executed successfully.
Events
-
Db authenticated event
Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated.
Type:
- object
-
Db close event
Emitted after a socket closed against a single server or mongos proxy.
Type:
-
Db error event
Emitted after an error occurred against a single server or mongos proxy.
Type:
-
Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.
- Server: Emitted when the driver has connected to the single server and has authenticated.
- ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
- Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
Type:
-
Db parseError event
The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.
Type:
-
Db reconnect event
- Server: Emitted when the driver has reconnected and re-authenticated.
- ReplicaSet: N/A
- Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
Type:
- object
-
Db timeout event
Emitted after a socket timeout occurred against a single server or mongos proxy.
Type: