fullResult {Boolean, default:false}, returns the full result document (document returned will differ by server version)

insert(docs[, options][, callback])

Arguments:

docs (array) –

[options] (object) – optional options for insert command

[callback] (function) – optional callback for the function, must be provided when using a writeconcern

Returns:

collection

Examples

A simple document insert example, not using safe mode to ensure document persistance on MongoDB

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Fetch a collection to insert document intodb.open(function(err,db){varcollection=db.collection("simple_document_insert_collection_no_safe");// Insert a single documentcollection.insert({hello:'world_no_safe'});// Wait for a second before finishing up, to ensure we have written the item to disksetTimeout(function(){// Fetch the documentcollection.findOne({hello:'world_no_safe'},function(err,item){assert.equal(null,err);assert.equal('world_no_safe',item.hello);db.close();})},100);});

varDb=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');vardb=newDb('test',newServer('localhost',27017));db.open(function(err,db){// Fetch a collection to insert document intovarcollection=db.collection("batch_document_insert_collection_safe");// Insert a single documentcollection.insert([{hello:'world_safe1'},{hello:'world_safe2'}],{w:1},function(err,result){assert.equal(null,err);// Fetch the documentcollection.findOne({hello:'world_safe2'},function(err,item){assert.equal(null,err);assert.equal('world_safe2',item.hello);db.close();})});});

Example of inserting a document containing functions

varDb=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');vardb=newDb('test',newServer('localhost',27017));db.open(function(err,db){// Fetch a collection to insert document intovarcollection=db.collection("simple_document_insert_with_function_safe");// Insert a single documentcollection.insert({hello:'world',func:function(){}},{w:1,serializeFunctions:true},function(err,result){assert.equal(null,err);// Fetch the documentcollection.findOne({hello:'world'},function(err,item){assert.equal(null,err);assert.ok("function() {}",item.code);db.close();})});});

Example of using keepGoing to allow batch insert to complete even when there are illegal documents in the batch

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Only run the rest of the code if we have a mongodb server with version >= 1.9.1db.open(function(err,db){// Create a collectionvarcollection=db.collection('keepGoingExample');// Add an unique index to title to force errors in the batch insertcollection.ensureIndex({title:1},{unique:true},function(err,indexName){// Insert some intial data into the collectioncollection.insert([{name:"Jim"},{name:"Sarah",title:"Princess"}],{w:1},function(err,result){// Force keep going flag, ignoring unique index issuecollection.insert([{name:"Jim"},{name:"Sarah",title:"Princess"},{name:'Gump',title:"Gump"}],{w:1,keepGoing:true},function(err,result){// Count the number of documents left (should not include the duplicates)collection.count(function(err,count){assert.equal(3,count);})});});});});

fullResult {Boolean, default:false}, returns the full result document (document returned will differ by server version)

remove([selector][, options], [callback])

Arguments:

[selector] (object) – optional select, no selector is equivalent to removing all documents.

[options] (object) – additional options during remove.

[callback] (function) – must be provided if you performing a remove with a writeconcern

Returns:

null

Examples

An example removing all documents in a collection not using safe mode

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Fetch a collection to insert document intodb.collection("remove_all_documents_no_safe",function(err,collection){// Insert a bunch of documentscollection.insert([{a:1},{b:2}],{w:1},function(err,result){assert.equal(null,err);// Remove all the documentcollection.remove();// Fetch all resultscollection.find().toArray(function(err,items){assert.equal(null,err);assert.equal(0,items.length);db.close();});});})});

An example removing a subset of documents using safe mode to ensure removal of documents

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Fetch a collection to insert document intodb.collection("remove_subset_of_documents_safe",function(err,collection){// Insert a bunch of documentscollection.insert([{a:1},{b:2}],{w:1},function(err,result){assert.equal(null,err);// Remove all the documentcollection.remove({a:1},{w:1},function(err,numberOfRemovedDocs){assert.equal(null,err);assert.equal(1,numberOfRemovedDocs);db.close();});});})});

dropTarget {Boolean, default:false}, drop the target name collection if it previously exists.

rename(newName[, options], callback)

Arguments:

newName (string) – the new name of the collection.

[options] (object) – returns option results.

callback (function) – the callback accepting the result

Returns:

null

Examples

An example of illegal and legal renaming of a collection

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Open a couple of collectionsdb.createCollection('test_rename_collection',function(err,collection1){db.createCollection('test_rename_collection2',function(err,collection2){// Attemp to rename a collection to a numbertry{collection1.rename(5,function(err,collection){});}catch(err){assert.ok(errinstanceofError);assert.equal("collection name must be a String",err.message);}// Attemp to rename a collection to an empty stringtry{collection1.rename("",function(err,collection){});}catch(err){assert.ok(errinstanceofError);assert.equal("collection names cannot be empty",err.message);}// Attemp to rename a collection to an illegal name including the character $try{collection1.rename("te$t",function(err,collection){});}catch(err){assert.ok(errinstanceofError);assert.equal("collection names must not contain '$'",err.message);}// Attemp to rename a collection to an illegal name starting with the character .try{collection1.rename(".test",function(err,collection){});}catch(err){assert.ok(errinstanceofError);assert.equal("collection names must not start or end with '.'",err.message);}// Attemp to rename a collection to an illegal name ending with the character .try{collection1.rename("test.",function(err,collection){});}catch(err){assert.ok(errinstanceofError);assert.equal("collection names must not start or end with '.'",err.message);}// Attemp to rename a collection to an illegal name with an empty middle nametry{collection1.rename("tes..t",function(err,collection){});}catch(err){assert.equal("collection names cannot be empty",err.message);}// Insert a couple of documentscollection1.insert([{'x':1},{'x':2}],{w:1},function(err,docs){// Attemp to rename the first collection to the second one, this will failcollection1.rename('test_rename_collection2',function(err,collection){assert.ok(errinstanceofError);assert.ok(err.message.length>0);// Attemp to rename the first collection to a name that does not exist// this will be succesfulcollection1.rename('test_rename_collection3',function(err,collection){assert.equal("test_rename_collection3",collection.collectionName);// Ensure that the collection is pointing to the new onecollection1.count(function(err,count){assert.equal(2,count);db.close();});});});})});});});

[callback] (function) – must be provided if you performing an update with a writeconcern

Returns:

null

Examples

Example of a simple document save with safe set to false

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Fetch the collectionvarcollection=db.collection("save_a_simple_document");// Save a document with no safe optioncollection.save({hello:'world'});// Wait for a secondsetTimeout(function(){// Find the saved documentcollection.findOne({hello:'world'},function(err,item){assert.equal(null,err);assert.equal('world',item.hello);db.close();});},1000);});

Example of a simple document save and then resave with safe set to true

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Fetch the collectionvarcollection=db.collection("save_a_simple_document_modify_it_and_resave_it");// Save a document with no safe optioncollection.save({hello:'world'},{w:0},function(err,result){// Find the saved documentcollection.findOne({hello:'world'},function(err,item){assert.equal(null,err);assert.equal('world',item.hello);// Update the documentitem['hello2']='world2';// Save the item with the additional fieldcollection.save(item,{w:1},function(err,result){// Find the changed documentcollection.findOne({hello:'world'},function(err,item){assert.equal(null,err);assert.equal('world',item.hello);assert.equal('world2',item.hello2);db.close();});});});});});

fullResult {Boolean, default:false}, returns the full result document (document returned will differ by server version)

update(selector, document[, options][, callback])

Arguments:

selector (object) – the query to select the document/documents to be updated

document (object) – the fields/vals to be updated, or in the case of an upsert operation, inserted.

[options] (object) – additional options during update.

[callback] (function) – must be provided if you performing an update with a writeconcern

Returns:

null

Examples

Example of a simple document update with safe set to false on an existing document

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Get a collectiondb.collection('update_a_simple_document',function(err,collection){// Insert a document, then update itcollection.insert({a:1},{w:1},function(err,doc){// Update the document with an atomic operatorcollection.update({a:1},{$set:{b:2}});// Wait for a second then fetch the documentsetTimeout(function(){// Fetch the document that we modifiedcollection.findOne({a:1},function(err,item){assert.equal(null,err);assert.equal(1,item.a);assert.equal(2,item.b);db.close();});},1000);})});});

Example of a simple document update using upsert (the document will be inserted if it does not exist)

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Get a collectiondb.collection('update_a_simple_document_upsert',function(err,collection){// Update the document using an upsert operation, ensuring creation if it does not existcollection.update({a:1},{b:2,a:1},{upsert:true,w:1},function(err,result){assert.equal(null,err);assert.equal(1,result);// Fetch the document that we modified and check if it got inserted correctlycollection.findOne({a:1},function(err,item){assert.equal(null,err);assert.equal(1,item.a);assert.equal(2,item.b);db.close();});});});});

Example of an update across multiple documents using the multi option.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Get a collectiondb.collection('update_a_simple_document_multi',function(err,collection){// Insert a couple of documentationscollection.insert([{a:1,b:1},{a:1,b:2}],{w:1},function(err,result){// Update multiple documents using the multi optioncollection.update({a:1},{$set:{b:0}},{w:1,multi:true},function(err,numberUpdated){assert.equal(null,err);assert.equal(2,numberUpdated);// Fetch all the documents and verify that we have changed the b valuecollection.find().toArray(function(err,items){assert.equal(null,err);assert.equal(1,items[0].a);assert.equal(0,items[0].b);assert.equal(1,items[1].a);assert.equal(0,items[1].b);db.close();});})});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured.

Returns:

null

Examples

Example of running the distinct command against a collection

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Crete the collection for the distinct exampledb.createCollection('simple_key_based_distinct',function(err,collection){// Insert documents to perform distinct againstcollection.insert([{a:0,b:{c:'a'}},{a:1,b:{c:'b'}},{a:1,b:{c:'c'}},{a:2,b:{c:'a'}},{a:3},{a:3}],{w:1},function(err,ids){// Peform a distinct query against the a fieldcollection.distinct('a',function(err,docs){assert.deepEqual([0,1,2,3],docs.sort());// Perform a distinct query against the sub-field b.ccollection.distinct('b.c',function(err,docs){assert.deepEqual(['a','b','c'],docs.sort());db.close();});});})});});

Example of running the distinct command against a collection with a filter query

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Crete the collection for the distinct exampledb.createCollection('simple_key_based_distinct_sub_query_filter',function(err,collection){// Insert documents to perform distinct againstcollection.insert([{a:0,b:{c:'a'}},{a:1,b:{c:'b'}},{a:1,b:{c:'c'}},{a:2,b:{c:'a'}},{a:3},{a:3},{a:5,c:1}],{w:1},function(err,ids){// Peform a distinct query with a filter against the documentscollection.distinct('a',{c:1},function(err,docs){assert.deepEqual([5],docs.sort());db.close();});})});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured.

Returns:

null

Examples

Example of running simple count commands against a collection.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Crete the collection for the distinct exampledb.createCollection('simple_count_example',function(err,collection){// Insert documents to perform distinct againstcollection.insert([{a:1},{a:2},{a:3},{a:4,b:1}],{w:1},function(err,ids){// Perform a total count commandcollection.count(function(err,count){assert.equal(null,err);assert.equal(4,count);// Peform a partial account where b=1collection.count({b:1},function(err,count){assert.equal(null,err);assert.equal(1,count);db.close();});});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured.

Returns:

null

Examples

Example of a simple document save and then resave with safe set to true

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('test_other_drop',function(err,collection){assert.equal(null,err);// Drop the collectioncollection.drop(function(err,reply){// Ensure we don't have the collection in the set of namesdb.collectionNames(function(err,replies){varfound=false;// For each collection in the list of collection names in this db look for the// dropped collectionreplies.forEach(function(document){if(document.name=="test_other_drop"){found=true;return;}});// Ensure the collection is not foundassert.equal(false,found);// Let's close the dbdb.close();});});});});

if multiple docs match, choose the first one in the specified sort order as the object to manipulate

doc (object) –

the fields/vals to be updated

[options] (object) – additional options during update.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured.

Returns:

null

Examples

A whole set of different ways to use the findAndModify command.

The first findAndModify command modifies a document and returns the modified document back.
The second findAndModify command removes the document.
The second findAndModify command upserts a document and returns the new document.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_find_and_modify_operations_',function(err,collection){assert.equal(null,err);// Insert some test documentationscollection.insert([{a:1},{b:1},{c:1}],{w:1},function(err,result){assert.equal(null,err);// Simple findAndModify command returning the new documentcollection.findAndModify({a:1},[['a',1]],{$set:{b1:1}},{new:true},function(err,doc){assert.equal(null,err);assert.equal(1,doc.a);assert.equal(1,doc.b1);// Simple findAndModify command returning the new document and// removing it at the same timecollection.findAndModify({b:1},[['b',1]],{$set:{b:2}},{remove:true},function(err,doc){// Verify that the document is gonecollection.findOne({b:1},function(err,item){assert.equal(null,err);assert.equal(null,item);// Simple findAndModify command performing an upsert and returning the new document// executing the command safelycollection.findAndModify({d:1},[['b',1]],{d:1,f:1},{new:true,upsert:true,w:1},function(err,doc){assert.equal(null,err);assert.equal(1,doc.d);assert.equal(1,doc.f);db.close();})});});});});});});

if multiple docs match, choose the first one in the specified sort order as the object to manipulate

[options] (object) – additional options during update.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured.

Returns:

null

Examples

An example of using findAndRemove

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_find_and_modify_operations_2',function(err,collection){assert.equal(null,err);// Insert some test documentationscollection.insert([{a:1},{b:1,d:1},{c:1}],{w:1},function(err,result){assert.equal(null,err);// Simple findAndModify command returning the old document and// removing it at the same timecollection.findAndRemove({b:1},[['b',1]],function(err,doc){assert.equal(null,err);assert.equal(1,doc.b);assert.equal(1,doc.d);// Verify that the document is gonecollection.findOne({b:1},function(err,item){assert.equal(null,err);assert.equal(null,item);db.close();});});});});});

numberOfRetries {Number, default:5}, if using awaidata specifies the number of times to retry on timeout.

partial {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system

maxTimeMS {Number}, number of miliseconds to wait before aborting the query.

find(query[, options], callback)

Arguments:

query (object) – query object to locate the object to modify

[options] (object) – additional options during update.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured.

Returns:

cursor returns a cursor to the query

Examples

A simple query using the find method on the collection.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_query',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the testingcollection.insert([{a:1},{a:2},{a:3}],{w:1},function(err,result){assert.equal(null,err);// Peform a simple find and return all the documentscollection.find().toArray(function(err,docs){assert.equal(null,err);assert.equal(3,docs.length);db.close();});});});});

A simple query showing the explain for a query

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_explain_query',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the testingcollection.insert([{a:1},{a:2},{a:3}],{w:1},function(err,result){assert.equal(null,err);// Peform a simple find and return all the documentscollection.find({},{explain:true}).toArray(function(err,docs){assert.equal(null,err);assert.equal(1,docs.length);db.close();});});});});

A simple query showing skip and limit

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_limit_skip_query',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the testingcollection.insert([{a:1,b:1},{a:2,b:2},{a:3,b:3}],{w:1},function(err,result){assert.equal(null,err);// Peform a simple find and return all the documentscollection.find({},{skip:1,limit:1,fields:{b:1}}).toArray(function(err,docs){assert.equal(null,err);assert.equal(1,docs.length);assert.equal(null,docs[0].a);assert.equal(2,docs[0].b);db.close();});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured.

Returns:

cursor returns a cursor to the query

Examples

A simple query using findOne

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_limit_skip_find_one_query',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the testingcollection.insert([{a:1,b:1},{a:2,b:2},{a:3,b:3}],{w:1},function(err,result){assert.equal(null,err);// Peform a simple find and return all the documentscollection.findOne({a:2},{fields:{b:1}},function(err,doc){assert.equal(null,err);assert.equal(null,doc.a);assert.equal(2,doc.b);db.close();});});});});

dropDups {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value

min {Number}, for geospatial indexes set the lower bound for the co-ordinates.

max {Number}, for geospatial indexes set the high bound for the co-ordinates.

v {Number}, specify the format version of the indexes.

expireAfterSeconds {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)

name {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured.

Returns:

null

Examples

A simple createIndex using a simple single field index

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('simple_index_test',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.insert([{a:1},{a:2},{a:3},{a:4}],{w:1},function(err,result){assert.equal(null,err);// Create an index on the a fieldcollection.createIndex('a',{w:1},function(err,indexName){assert.equal("a_1",indexName);// Peform a query, with explain to show we hit the querycollection.find({a:2},{explain:true}).toArray(function(err,explanation){assert.deepEqual([[2,2]],explanation[0].indexBounds.a);db.close();});});});});});

A more complex createIndex using a compound unique index in the background and dropping duplicated documents

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('more_complex_index_test',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.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);varoptions={unique:true,background:true,dropDups:true,w:1};// Create an index on the a fieldcollection.createIndex({a:1,b:1},options,function(err,indexName){assert.ok(!options.readPreference);// Show that duplicate records got droppedcollection.find({}).toArray(function(err,items){assert.equal(null,err);assert.equal(4,items.length);// Peform a query, with explain to show we hit the querycollection.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();});})});});});});

dropDups {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value

min {Number}, for geospatial indexes set the lower bound for the co-ordinates.

max {Number}, for geospatial indexes set the high bound for the co-ordinates.

v {Number}, specify the format version of the indexes.

expireAfterSeconds {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)

name {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured.

Returns:

null

Examples

A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('more_complex_ensure_index_test',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.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 fieldcollection.ensureIndex({a:1,b:1},{unique:true,background:true,dropDups:true,w:1},function(err,indexName){// Show that duplicate records got droppedcollection.find({}).toArray(function(err,items){assert.equal(null,err);assert.equal(4,items.length);// Peform a query, with explain to show we hit the querycollection.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();});})});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured.

Returns:

null

Examples

An examples showing the information returned by indexInformation

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('more_index_information_test',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.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 fieldcollection.ensureIndex({a:1,b:1},{unique:true,background:true,dropDups:true,w:1},function(err,indexName){// Fetch basic indexInformation for collectioncollection.indexInformation(function(err,indexInformation){assert.deepEqual([['_id',1]],indexInformation._id_);assert.deepEqual([['a',1],['b',1]],indexInformation.a_1_b_1);// Fetch full index informationcollection.indexInformation({full:true},function(err,indexInformation){assert.deepEqual({_id:1},indexInformation[0].key);assert.deepEqual({a:1,b:1},indexInformation[1].key);db.close();});});});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured.

Returns:

null

Examples

An examples showing the creation and dropping of an index

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('create_and_drop_an_index',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.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 fieldcollection.ensureIndex({a:1,b:1},{unique:true,background:true,dropDups:true,w:1},function(err,indexName){// Drop the indexcollection.dropIndex("a_1_b_1",function(err,result){assert.equal(null,err);// Verify that the index is gonecollection.indexInformation(function(err,indexInformation){assert.deepEqual([['_id',1]],indexInformation._id_);assert.equal(null,indexInformation.a_1_b_1);db.close();});});});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured.

Returns:

null

Examples

An example showing how to force a reindex of a collection.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a collection we want to drop laterdb.createCollection('shouldCorrectlyForceReindexOnCollection',function(err,collection){assert.equal(null,err);// Insert a bunch of documents for the indexcollection.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 fieldcollection.ensureIndex({a:1,b:1},{unique:true,background:true,dropDups:true,w:1},function(err,indexName){// Force a reindex of the collectioncollection.reIndex(function(err,result){assert.equal(null,err);assert.equal(true,result);// Verify that the index is gonecollection.indexInformation(function(err,indexInformation){assert.deepEqual([['_id',1]],indexInformation._id_);assert.deepEqual([['a',1],['b',1]],indexInformation.a_1_b_1);db.close();});});});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured.

finalize (function) – an optional function to be run on each item in the result set just before the item is returned.

command (boolean) – specify if you wish to run using the internal group command or using eval, default is true.

[options] (object) – additional options during update.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured.

Returns:

null

Examples

A whole lot of different wayt to execute the group command

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a test collectiondb.createCollection('test_group',function(err,collection){// Peform a simple group by on an empty collectioncollection.group([],{},{"count":0},"function (obj, prev) { prev.count++; }",function(err,results){assert.deepEqual([],results);// Trigger some inserts on the collectioncollection.insert([{'a':2},{'b':5},{'a':1}],{w:1},function(err,ids){// Perform a group countcollection.group([],{},{"count":0},"function (obj, prev) { prev.count++; }",function(err,results){assert.equal(3,results[0].count);// Pefrom a group count using the eval methodcollection.group([],{},{"count":0},"function (obj, prev) { prev.count++; }",false,function(err,results){assert.equal(3,results[0].count);// Group with a conditionalcollection.group([],{'a':{'$gt':1}},{"count":0},"function (obj, prev) { prev.count++; }",function(err,results){// Resultsassert.equal(1,results[0].count);// Group with a conditional using the EVAL methodcollection.group([],{'a':{'$gt':1}},{"count":0},"function (obj, prev) { prev.count++; }",false,function(err,results){// Resultsassert.equal(1,results[0].count);// Insert some more test datacollection.insert([{'a':2},{'b':3}],{w:1},function(err,ids){// Do a Group by field acollection.group(['a'],{},{"count":0},"function (obj, prev) { prev.count++; }",function(err,results){// Resultsassert.equal(2,results[0].a);assert.equal(2,results[0].count);assert.equal(null,results[1].a);assert.equal(2,results[1].count);assert.equal(1,results[2].a);assert.equal(1,results[2].count);// Do a Group by field acollection.group({'a':true},{},{"count":0},function(obj,prev){prev.count++;},true,function(err,results){// Resultsassert.equal(2,results[0].a);assert.equal(2,results[0].count);assert.equal(null,results[1].a);assert.equal(2,results[1].count);assert.equal(1,results[2].a);assert.equal(1,results[2].count);// Correctly handle illegal functioncollection.group([],{},{},"5 ++ 5",function(err,results){assert.ok(err.message!=null);// Use a function to select the keys used to group byvarkeyf=function(doc){return{a:doc.a};};collection.group(keyf,{a:{$gt:0}},{"count":0,"value":0},function(obj,prev){prev.count++;prev.value+=obj.a;},true,function(err,results){// Resultsresults.sort(function(a,b){returnb.count-a.count;});assert.equal(2,results[0].count);assert.equal(2,results[0].a);assert.equal(4,results[0].value);assert.equal(1,results[1].count);assert.equal(1,results[1].a);assert.equal(1,results[1].value);// Use a Code object to select the keys used to group byvarkeyf=newCode(function(doc){return{a:doc.a};});collection.group(keyf,{a:{$gt:0}},{"count":0,"value":0},function(obj,prev){prev.count++;prev.value+=obj.a;},true,function(err,results){// Resultsresults.sort(function(a,b){returnb.count-a.count;});assert.equal(2,results[0].count);assert.equal(2,results[0].a);assert.equal(4,results[0].value);assert.equal(1,results[1].count);assert.equal(1,results[1].a);assert.equal(1,results[1].value);// Correctly handle illegal function when using the EVAL methodcollection.group([],{},{},"5 ++ 5",false,function(err,results){assert.ok(err.message!=null);db.close();});});});});});});});});});});});});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured.

Returns:

null

Examples

An example returning the options for a collection.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a test collection that we are getting the options back fromdb.createCollection('test_collection_options',{'capped':true,'size':1024},function(err,collection){assert.ok(collectioninstanceofCollection);assert.equal('test_collection_options',collection.collectionName);// Let's fetch the collection optionscollection.options(function(err,options){assert.equal(true,options.capped);assert.ok(options.size>=1024);db.close();});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured.

Returns:

null

Examples

An example showing how to establish if it’s a capped collection

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a test collection that we are getting the options back fromdb.createCollection('test_collection_is_capped',{'capped':true,'size':1024},function(err,collection){assert.ok(collectioninstanceofCollection);assert.equal('test_collection_is_capped',collection.collectionName);// Let's fetch the collection optionscollection.isCapped(function(err,capped){assert.equal(true,capped);db.close();});});});

indexNames (string) – check if one or more indexes exist on the collection.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured.

Returns:

null

Examples

An example showing the use of the indexExists function for a single index name and a list of index names.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Create a test collection that we are getting the options back fromdb.createCollection('test_collection_index_exists',{w:1},function(err,collection){assert.equal(null,err);// Create an index on the collectioncollection.createIndex('a',{w:1},function(err,indexName){// Let's test to check if a single index existscollection.indexExists("a_1",function(err,result){assert.equal(true,result);// Let's test to check if multiple indexes are availablecollection.indexExists(["a_1","_id_"],function(err,result){assert.equal(true,result);// Check if a non existing index existscollection.indexExists("c_1",function(err,result){assert.equal(false,result);db.close();});});});});});});

x (number) – point to search on the x axis, ensure the indexes are ordered in the same order.

y (number) – point to search on the y axis, ensure the indexes are ordered in the same order.

[options] (objects) – options for the map reduce job.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured.

Returns:

null

Examples

Example of a simple geoNear query across some documents

varDb=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');vardb=configuration.newDbInstance({w:0},{poolSize:1});// Establish connection to dbdb.open(function(err,db){// Fetch the collectionvarcollection=db.collection("simple_geo_near_command");// Add a location based indexcollection.ensureIndex({loc:"2d"},function(err,result){// Save a new location tagged documentcollection.insert([{a:1,loc:[50,30]},{a:1,loc:[30,50]}],{w:1},function(err,result){// Use geoNear command to find documentcollection.geoNear(50,50,{query:{a:1},num:1},function(err,docs){assert.equal(1,docs.results.length);db.close();});});});});

x (number) – point to search on the x axis, ensure the indexes are ordered in the same order.

y (number) – point to search on the y axis, ensure the indexes are ordered in the same order.

[options] (objects) – options for the map reduce job.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured.

Returns:

null

Examples

Example of a simple geoHaystackSearch query across some documents

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Fetch the collectionvarcollection=db.collection("simple_geo_haystack_command");// Add a location based indexcollection.ensureIndex({loc:"geoHaystack",type:1},{bucketSize:1},function(err,result){// Save a new location tagged documentcollection.insert([{a:1,loc:[50,30]},{a:1,loc:[30,50]}],{w:1},function(err,result){// Use geoNear command to find documentcollection.geoHaystackSearch(50,50,{search:{a:1},limit:1,maxDistance:100},function(err,docs){assert.equal(1,docs.results.length);db.close();});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured.

Returns:

null

Examples

Example of retrieving a collections indexes

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Crete the collection for the distinct exampledb.createCollection('simple_key_based_distinct',function(err,collection){// Create a geo 2d indexcollection.ensureIndex({loc:"2d"},{w:1},function(err,result){assert.equal(null,err);// Create a simple single field indexcollection.ensureIndex({a:1},{w:1},function(err,result){assert.equal(null,err);// List all of the indexes on the collectioncollection.indexes(function(err,indexes){assert.equal(3,indexes.length);db.close();});})})});});

allowDiskUse {Boolean, default:false}, allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).

aggregate(array[, options], callback)

Arguments:

array (array) – containing all the aggregation framework commands for the execution.

[options] (object) – additional options during update.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured.

Returns:

null

Examples

Correctly call the aggregation framework using a pipeline in an Array.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyExecuteSimpleAggregationPipelineUsingArray');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arraycollection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],function(err,result){assert.equal(null,err);assert.equal('good',result[0]._id.tags);assert.deepEqual(['bob'],result[0].authors);assert.equal('fun',result[1]._id.tags);assert.deepEqual(['bob'],result[1].authors);db.close();});});});

Correctly call the aggregation framework using a pipeline expressed as an argument list.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyExecuteSimpleAggregationPipelineUsingArguments');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as function call parameters// instead of an Array.collection.aggregate({$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}},function(err,result){assert.equal(null,err);assert.equal('good',result[0]._id.tags);assert.deepEqual(['bob'],result[0].authors);assert.equal('fun',result[1]._id.tags);assert.deepEqual(['bob'],result[1].authors);db.close();});});});

Correctly call the aggregation framework using a pipeline expressed as an argument list.

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyExecuteSimpleAggregationPipelineUsingArguments');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as function call parameters// instead of an Array.collection.aggregate({$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}},function(err,result){assert.equal(null,err);assert.equal('good',result[0]._id.tags);assert.deepEqual(['bob'],result[0].authors);assert.equal('fun',result[1]._id.tags);assert.deepEqual(['bob'],result[1].authors);db.close();});});});

Correctly call the aggregation framework to return a cursor

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyDoAggWithCursorGet');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arrayvarcursor=collection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],{cursor:{batchSize:100}});// Iterate over all the items in the cursorcursor.get(function(err,results){assert.equal(null,err);assert.equal('good',results[0]._id.tags);assert.deepEqual(['bob'],results[0].authors);assert.equal('fun',results[1]._id.tags);assert.deepEqual(['bob'],results[1].authors);db.close();});});});

Correctly call the aggregation framework to return a cursor and call explain

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyDoAggWithCursorGet');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arrayvarcursor=collection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],{cursor:{batchSize:100}});// Iterate over all the items in the cursorcursor.explain(function(err,results){assert.equal(null,err);assert.equal(4,results.length);db.close();});});});

Correctly call the aggregation framework to return a cursor with batchSize 1 and get the first result using next

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyDoAggWithCursorGet');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arrayvarcursor=collection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],{cursor:{batchSize:1}});// Iterate over all the items in the cursorcursor.next(function(err,result){assert.equal(null,err);assert.equal('good',result._id.tags);assert.deepEqual(['bob'],result.authors);db.close();});});});

Correctly call the aggregation framework and write the results to a new collection

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyDoAggWithCursorGet');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arraycollection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],{out:"testingOutCollectionForAggregation"},function(err,results){assert.equal(null,err);assert.equal(0,results.length);db.close();});});});

Correctly use allowDiskUse when performing an aggregation

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Some docs for insertionvardocs=[{title:"this is my title",author:"bob",posted:newDate(),pageViews:5,tags:["fun","good","fun"],other:{foo:5},comments:[{author:"joe",text:"this is cool"},{author:"sam",text:"this is bad"}]}];// Create a collectionvarcollection=db.collection('shouldCorrectlyDoAggWithCursorGet');// Insert the docscollection.insert(docs,{w:1},function(err,result){// Execute aggregate, notice the pipeline is expressed as an Arraycollection.aggregate([{$project:{author:1,tags:1}},{$unwind:"$tags"},{$group:{_id:{tags:"$tags"},authors:{$addToSet:"$author"}}}],{allowDiskUse:true},function(err,results){assert.equal(null,err);assert.equal('good',results[0]._id.tags);assert.deepEqual(['bob'],results[0].authors);assert.equal('fun',results[1]._id.tags);assert.deepEqual(['bob'],results[1].authors);db.close();});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured.

Returns:

null

Examples

Example of retrieving a collections stats

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){// Crete the collection for the distinct exampledb.createCollection('collection_stats_test',function(err,collection){// Insert some documentscollection.insert([{a:1},{hello:'world'}],{w:1},function(err,result){// Retrieve the statistics for the collectioncollection.stats(function(err,stats){assert.equal(2,stats.count);db.close();});});});});

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a UnorderedBulkOperation object.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a OrderedBulkOperation object.

callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be an array of CommandCursor instances.

Returns:

orderedbulkoperation

Examples

A parallelCollectionScan example

varDb=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');vardb=newDb('test',newServer('localhost',27017));// Establish connection to dbdb.open(function(err,db){vardocs=[];// Insert some documentsfor(vari=0;i<2000;i++){docs.push({a:i});}// Get the collectionvarcollection=db.collection('parallelCollectionScan');// Insert 1000 documents in a batchcollection.insert(docs,function(err,result){varresults=[];varnumCursors=3;// Execute parallelCollectionScan commandcollection.parallelCollectionScan({numCursors:numCursors},function(err,cursors){assert.equal(null,err);assert.ok(cursors!=null);assert.ok(cursors.length>0);for(vari=0;i<cursors.length;i++){cursors[i].get(function(err,items){assert.equal(err,null);// Add docs to results arrayresults=results.concat(items);numCursors=numCursors-1;// No more cursors let's ensure we got all resultsif(numCursors==0){assert.equal(docs.length,results.length);db.close();}});}});});});