Create a new Db instance.
- class Db()¶
Arguments:
- databaseName (string) – name of the database.
- serverConfig (object) – server config object.
- [options] (object) – additional options for the collection.
Constant Name | Value | Description |
---|---|---|
Db.DEFAULT_URL | ‘mongodb://localhost:27017/default’ | Default URL |
Initialize the database connection.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of a simple single server db connection
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); db.on('close', test.done.bind(test)); db.close(); });Simple replicaset connection setup, requires a running replicaset on the correct ports
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var replSet = new ReplSetServers([ new Server('localhost', 30000), new Server('localhost', 30001), new Server('localhost', 30002) ]); var db = new Db('integration_test_', replSet, {w:0}); db.open(function(err, p_db) { assert.equal(null, err); p_db.close(); });Example of Read Preference usage at the query level.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var replSet = new ReplSetServers([ new Server('localhost', 30000), new Server('localhost', 30001), new Server('localhost', 30002) ]); // Create db instance var db = new Db('integration_test_', replSet, {w:0, native_parser: (process.env['TEST_NATIVE'] != null)}); // Trigger test once whole set is up db.on("fullsetup", function() { // Rip out secondaries forcing an attempt to read from the primary db.serverConfig._state.secondaries = {}; // Grab the collection db.collection("read_preference_replicaset_test_0", function(err, collection) { // Attempt to read (should fail due to the server not being a primary); collection.find().setReadPreference(ReadPreference.SECONDARY).toArray(function(err, items) { assert.ok(err != null); assert.equal("No replica set secondary available for query with ReadPreference SECONDARY", err.message); // Does not get called or we don't care db.close(); }); }); }); // Connect to the db db.open(function(err, p_db) { db = p_db; });A Simple example off connecting to Mongos with a list of alternative proxies.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); // Set up mongos connection var mongos = new Mongos([ new Server("localhost", 50000, { auto_reconnect: true }), new Server("localhost", 50001, { auto_reconnect: true }) ]) // Connect using the mongos connections var db = new Db('integration_test_', mongos, {w:0}); db.open(function(err, db) { assert.equal(null, err); assert.ok(db != null); // Perform a simple insert into a collection var collection = db.collection("shard_test"); // Insert a simple doc collection.insert({test:1}, {w:1}, function(err, result) { assert.equal(null, err); collection.findOne({test:1}, {}, {readPreference:new ReadPreference(ReadPreference.SECONDARY)}, function(err, item) { assert.equal(null, err); assert.equal(1, item.test); db.close(); }) }); });
Create a new Db instance sharing the current socket connections.
Arguments: |
|
---|---|
Returns: | db a db instance using the new database. |
Examples
Simple example connecting to two different databases sharing the socket connections below.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.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) { assert.equal(1, count); multipleColl2.count(function(err, count) { assert.equal(1, count); db.close(); }); }); }); }); });
Close the current db connection, including all the child db instances. Emits close event and calls optional callback.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example that shows how to force close a db connection so it cannot be reused.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Fetch a collection var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb'); // Insert a document collection.insert({a:1}, {w:1}, function(err, result) { assert.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) { assert.equal('db closed by application', err.message); }); }); }); });An example of a simple single server db connection and close function
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Close the connection with a callback that is optional db.close(function(err, result) { assert.equal(null, err); }); });
Access the Admin database
Arguments: |
|
---|---|
Returns: | admin the admin db object. |
Examples
Example showing how to access the Admin database for admin level operations.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); db.open(function(err, db) { // Use the admin database for the operation var adminDb = db.admin() assert.ok(adminDb != null); db.close(); });
Returns a cursor to all the collection information.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of retrieving the information of all the collections.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Create a collection db.createCollection('test_collections_info', function(err, r) { assert.equal(null, err); // Return the information of a single collection name db.collectionsInfo("test_collections_info").toArray(function(err, items) { assert.equal(1, items.length); // Return the information of a all collections, using the callback format db.collectionsInfo(function(err, cursor) { // Turn the cursor into an array of results cursor.toArray(function(err, items) { assert.ok(items.length > 0); db.close(); }); }) }); }); });
Get the list of all collection names for the specified db
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of retrieving the collection names for a database.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Create a collection db.createCollection('test_collections_info', function(err, r) { assert.equal(null, err); // Return the information of a single collection name db.collectionNames("test_collections_info", function(err, items) { assert.equal(1, items.length); // Return the information of a all collections, using the callback format db.collectionNames(function(err, items) { assert.ok(items.length > 0); db.close(); }); }); }); });
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’);
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of retrieving a collection from a db using the collection function.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.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) { assert.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) { assert.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) { assert.equal(null, err); db.close(); }); }); }); }); });
Fetch all collections for the current db.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of retrieving all collections for a db as Collection objects
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Create the collection db.createCollection('test_correctly_access_collections2', function(err, result) { // Retry to get the collection, should work as it's now created db.collections(function(err, collections) { assert.equal(null, err); assert.ok(collections.length > 0); db.close(); }); }); });
Evaluate javascript on the server
Arguments: |
|
---|---|
Returns: | null |
Examples
A whole bunch of examples on how to use eval on the server.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(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) { assert.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) { assert.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], function(err, result) { // Locate the entry db.collection('test_eval', function(err, collection) { collection.findOne(function(err, item) { assert.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) { assert.equal(5, result); tests_done(); }); // Evaluate a function with no parameters passed in db.eval('function () {return 5;}', function(err, result) { assert.equal(5, result); tests_done(); }); // Evaluate a statement db.eval('2 + 3;', function(err, result) { assert.equal(5, result); tests_done(); }); // Evaluate a statement using the code object db.eval(new Code("2 + 3;"), function(err, result) { assert.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) { assert.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) { assert.equal(5, result); tests_done(); }); // Evaluate an illegal statement db.eval("5 ++ 5;", function(err, result) { assert.ok(err instanceof Error); assert.ok(err.message != null); tests_done(); // Let's close the db // db.close(); // test.done(); }); });Defining and calling a system level javascript function (NOT recommended, <a href=’http://www.mongodb.org/display/DOCS/Server-side+Code+Execution’>http://www.mongodb.org/display/DOCS/Server-side+Code+Execution</a>)
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Clean out the collection db.collection("system.js").remove({}, {w:1}, function(err, result) { assert.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) { assert.equal(null, err); db.eval("echo(5)", function(err, result) { assert.equal(null, err); assert.equal(5, result); db.close(); }); }); }); });
Dereference a dbref, against a db
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of dereferencing values.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Get a second db var secondDb = db.db('integration_tests_2'); // Create a dereference example secondDb.createCollection('test_deref_examples', function(err, collection) { // Insert a document in the collection collection.insert({'a':1}, {w:1}, function(err, ids) { // Let's build a db reference and resolve it var dbRef = new DBRef('test_deref_examples', ids[0]._id, 'integration_tests_2'); // Resolve it including a db resolve db.dereference(dbRef, function(err, item) { assert.equal(1, item.a); // Let's build a db reference and resolve it var dbRef = new DBRef('test_deref_examples', ids[0]._id); // Simple local resolve secondDb.dereference(dbRef, function(err, item) { assert.equal(1, item.a); db.close(); }); }); }); }); });
Logout user from server, fire off on all connections and remove all auth info
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of using the logout command for the database.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Add a user to the database db.addUser('user3', 'name', function(err, result) { assert.equal(null, err); // Authenticate db.authenticate('user3', 'name', function(err, result) { assert.equal(true, result); // Logout the db db.logout(function(err, result) { assert.equal(true, result); // Remove the user db.removeUser('user3', function(err, result) { assert.equal(true, result); db.close(); }); }); }); }); });
Authenticate a user against the server. authMechanism Options
- authMechanism {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of using the authenticate command.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Add a user to the database db.addUser('user2', 'name', function(err, result) { assert.equal(null, err); // Authenticate db.authenticate('user2', 'name', function(err, result) { assert.equal(true, result); db.close(); }); }); });
Add a user to the database.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of adding a user to the database.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Add a user to the database db.addUser('user', 'name', function(err, result) { assert.equal(null, err); db.close(); }); });
Remove a user from a database
Arguments: |
|
---|---|
Returns: | null |
Examples
An example of dereferencing values.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Add a user to the database db.addUser('user', 'name', function(err, result) { assert.equal(null, err); // Authenticate db.authenticate('user', 'name', function(err, result) { assert.equal(true, result); // Logout the db db.logout(function(err, result) { assert.equal(true, result); // Remove the user from the db db.removeUser('user', function(err, result) { // Authenticate db.authenticate('user', 'name', function(err, result) { assert.equal(false, result); db.close(); }); }); }); }); }); });
Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
Arguments: |
|
---|---|
Returns: | null |
Examples
A simple example showing the creation of a collection.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.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) { assert.equal(null, err); // Insert a document in the capped collection collection.insert({a:1}, {w:1}, function(err, result) { assert.equal(null, err); db.close(); }); }); });
Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server.
Arguments: |
|
---|---|
Returns: | null |
Examples
A simple example creating, dropping a collection and then verifying that the collection is gone.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Execute ping against the server db.command({ping:1}, function(err, result) { assert.equal(null, err); db.close(); }); });
Drop a collection from the database, removing it permanently. New accesses will create a new collection.
Arguments: |
|
---|---|
Returns: | null |
Examples
A simple example executing a command against the server.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Execute ping against the server db.command({ping:1}, function(err, result) { assert.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) { assert.equal(null, err); // Insert a document in the capped collection collection.insert({a:1}, {w:1}, function(err, result) { assert.equal(null, err); // Drop the collection from this world db.dropCollection("a_simple_create_drop_collection", function(err, result) { assert.equal(null, err); // Verify that the collection is gone db.collectionNames("a_simple_create_drop_collection", function(err, names) { assert.equal(0, names.length); db.close(); }); }); }); }); }); });
Rename a collection.
Arguments: |
|
---|---|
Returns: | null |
Examples
A simple example creating, dropping a collection and then verifying that the collection is gone.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); // Create a collection db.createCollection("simple_rename_collection", {w:1}, function(err, collection) { assert.equal(null, err); // Insert a document in the collection collection.insert({a:1}, {w:1}, function(err, result) { assert.equal(null, err); // Rename the collection db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) { assert.equal(null, err); // Retrieve the number of documents from the collection collection2.count(function(err, count) { assert.equal(1, count); // Verify that the collection is gone db.collectionNames("simple_rename_collection", function(err, names) { assert.equal(0, names.length); // Verify that the new collection exists db.collectionNames("simple_rename_collection_2", function(err, names) { assert.equal(1, names.length); db.close(); }); }); }); }); }); }); });
Creates an index on the collection.
Arguments: |
|
---|---|
Returns: | null |
Examples
A more complex createIndex using a compound unique index in the background and dropping duplicated documents
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('more_complex_index_test', function(err, collection) { assert.equal(null, err); // 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) { assert.equal(null, err); // Create an index on the a field db.createIndex('more_complex_index_test', {a:1, b:1} , {unique:true, background:true, dropDups:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { assert.equal(null, err); assert.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) { assert.equal(null, err); assert.ok(explanation[0].indexBounds.a != null); assert.ok(explanation[0].indexBounds.b != null); db.close(); }); }) }); }); }); });
Ensures that an index exists, if it does not it creates it
Arguments: |
|
---|---|
Returns: | null |
Examples
A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('more_complex_ensure_index_db_test', function(err, collection) { assert.equal(null, err); // 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) { assert.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, dropDups:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { assert.equal(null, err); assert.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) { assert.equal(null, err); assert.ok(explanation[0].indexBounds.a != null); assert.ok(explanation[0].indexBounds.b != null); db.close(); }); }) }); }); }); });
Returns the information available on allocated cursors.
Arguments: |
|
---|---|
Returns: | null |
Examples
A Simple example of returning current cursor information in MongoDB
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('cursor_information_collection', function(err, collection) { assert.equal(null, err); // Create a bunch of documents so we can force the creation of a cursor var docs = []; for(var i = 0; i < 1000; i++) { docs.push({a:'hello world hello world hello world hello world hello world hello world hello world hello world'}); } // Insert a bunch of documents for the index collection.insert(docs, {w:1}, function(err, result) { assert.equal(null, err); // Let's set a cursor var cursor = collection.find({}, {batchSize:10}); cursor.nextObject(function(err, item) { assert.equal(null, err); // Let's grab the information about the cursors on the database db.cursorInfo(function(err, cursorInformation) { assert.ok(cursorInformation.totalOpen > 0); db.close(); }); }); }); }); });
Drop an index on a collection.
Arguments: |
|
---|---|
Returns: | null |
Examples
An examples showing the creation and dropping of an index
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('create_and_drop_an_index', function(err, collection) { assert.equal(null, err); // 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) { assert.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, dropDups:true, w:1}, function(err, indexName) { // Drop the index db.dropIndex("create_and_drop_an_index", "a_1_b_1", function(err, result) { assert.equal(null, err); // Verify that the index is gone collection.indexInformation(function(err, indexInformation) { assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); assert.equal(null, indexInformation.a_1_b_1); db.close(); }); }); }); }); }); });
Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
Arguments: |
|
---|
Examples
An example showing how to force a reindex of a collection.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('create_and_drop_all_indexes', function(err, collection) { assert.equal(null, err); // 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, c:4}], {w:1}, function(err, result) { assert.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, dropDups:true, w:1}, function(err, indexName) { // Force a reindex of the collection db.reIndex('create_and_drop_all_indexes', function(err, result) { assert.equal(null, err); assert.equal(true, result); // Verify that the index is gone collection.indexInformation(function(err, indexInformation) { assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); assert.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); db.close(); }); }); }); }); }); });
Retrieves this collections index info.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example showing the information returned by indexInformation
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection we want to drop later db.createCollection('more_index_information_test', function(err, collection) { assert.equal(null, err); // 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) { assert.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, dropDups:true, w:1}, function(err, indexName) { // Fetch basic indexInformation for collection db.indexInformation('more_index_information_test', function(err, indexInformation) { assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); assert.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); // Fetch full index information collection.indexInformation({full:true}, function(err, indexInformation) { assert.deepEqual({ _id: 1 }, indexInformation[0].key); assert.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); db.close(); }); }); }); }); }); });
Drop a database.
Arguments: |
|
---|---|
Returns: | null |
Examples
An examples showing the dropping of a database
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { // Create a collection db.createCollection('more_index_information_test', function(err, collection) { assert.equal(null, err); // 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) { assert.equal(null, err); // Let's drop the database db.dropDatabase(function(err, result) { assert.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) assert.equal(false, found); db.close(); }); }, 2000); }); }); }); });
Get all the db statistics.
Arguments: |
|
---|---|
Returns: | null |
Examples
An example showing how to retrieve the db statistics
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db('test', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { assert.equal(null, err); db.stats(function(err, stats) { assert.equal(null, err); assert.ok(stats != null); db.close(); }) });
Connect to MongoDB using a url as documented at
docs.mongodb.org/manual/reference/connection-string/
Arguments: |
|
---|---|
Returns: | null |
Examples
Example of a simple url connection string, with no acknowledgement of writes.
var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); // Connect to the server Db.connect(configuration.url(), function(err, db) { assert.equal(null, err); db.close(); });