new Collection(){Collection}
Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
Properties:
Name | Type | Description |
---|---|---|
collectionName |
string | Get the collection name. |
namespace |
string | Get the full collection namespace. |
writeConcern |
object | The current write concern values. |
hint |
object | Get current index hint for collection. |
Returns:
Collection instance.Methods
-
aggregate(pipeline, options, callback){null|AggregationCursor}
-
Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
Name Type Default Description pipeline
object Array containing all the aggregation framework commands for the execution.
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
cursor
object null optional Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
Name Type Default Description batchSize
number null optional The batchSize for the cursor
explain
boolean false optional Explain returns the aggregation execution plan (requires mongodb 2.6 >).
allowDiskUse
boolean false optional allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
callback
Collection~resultCallback The command result callback
Examples
// Correctly call the aggregation framework using a pipeline in an Array. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Some docs for insertion var docs = [{ title : "this is my title", author : "bob", posted : new Date() , pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 }, comments : [ { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" } ]}]; // Create a collection var collection = db.collection('aggregationExample1'); // Insert the docs collection.insert(docs, {w: 1}, function(err, result) { // Execute aggregate, notice the pipeline is expressed as an Array collection.aggregate([ { $project : { author : 1, tags : 1 }}, { $unwind : "$tags" }, { $group : { _id : {tags : "$tags"}, authors : { $addToSet : "$author" } }} ], function(err, result) { test.equal(null, err); test.equal('good', result[0]._id.tags); test.deepEqual(['bob'], result[0].authors); test.equal('fun', result[1]._id.tags); test.deepEqual(['bob'], result[1].authors); db.close(); }); }); });
// Correctly call the aggregation using a cursor var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Some docs for insertion var docs = [{ title : "this is my title", author : "bob", posted : new Date() , pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 }, comments : [ { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" } ]}]; // Create a collection var collection = db.collection('aggregationExample2'); // Insert the docs collection.insert(docs, {w: 1}, function(err, result) { // Execute aggregate, notice the pipeline is expressed as an Array var cursor = collection.aggregate([ { $project : { author : 1, tags : 1 }}, { $unwind : "$tags" }, { $group : { _id : {tags : "$tags"}, authors : { $addToSet : "$author" } }} ], { cursor: { batchSize: 1 } }); // Get all the aggregation results cursor.toArray(function(err, docs) { test.equal(null, err); test.equal(2, docs.length); db.close(); }); }); });
// Correctly call the aggregation using a read stream var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Some docs for insertion var docs = [{ title : "this is my title", author : "bob", posted : new Date() , pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 }, comments : [ { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" } ]}]; // Create a collection var collection = db.collection('aggregationExample3'); // Insert the docs collection.insert(docs, {w: 1}, function(err, result) { // Execute aggregate, notice the pipeline is expressed as an Array var cursor = collection.aggregate([ { $project : { author : 1, tags : 1 }}, { $unwind : "$tags" }, { $group : { _id : {tags : "$tags"}, authors : { $addToSet : "$author" } }} ], { cursor: { batchSize: 1 } }); var count = 0; // Get all the aggregation results cursor.on('data', function(doc) { count = count + 1; }); cursor.once('end', function() { test.equal(2, count); db.close(); }); }); });
-
count(query, options, callback){null}
-
Count number of matching documents in the db to a query.
Name Type Default Description query
object The query for the count.
options
object null optional Optional settings.
Name Type Default Description limit
boolean null optional The limit of documents to count.
skip
boolean null optional The number of documents to skip for the count.
hint
string null optional An index name hint for the query.
readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callback
Collection~countCallback The command result callback
Example
// Example of running simple count commands against a collection. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Crete the collection for the distinct example var collection = db.collection('countExample1'); // Insert documents to perform distinct against collection.insert([{a:1}, {a:2} , {a:3}, {a:4, b:1}], {w: 1}, function(err, ids) { // Perform a total count command collection.count(function(err, count) { test.equal(null, err); test.equal(4, count); // Peform a partial account where b=1 collection.count({b:1}, function(err, count) { test.equal(null, err); test.equal(1, count); db.close(); }); }); }); });
-
createIndex(fieldOrSpec, options, callback){null}
-
Creates an index on the db and collection collection.
Name Type Default Description fieldOrSpec
string | object Defines the index.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
unique
boolean false optional Creates an unique index.
sparse
boolean false optional Creates a sparse index.
background
boolean false optional Creates the index in the background, yielding whenever possible.
dropDups
boolean false optional A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
min
number null optional For geospatial indexes set the lower bound for the co-ordinates.
max
number null optional For geospatial indexes set the high bound for the co-ordinates.
v
number null optional Specify the format version of the indexes.
expireAfterSeconds
number null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
number null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
callback
Collection~resultCallback The command result callback
Examples
// A more complex createIndex using a compound unique index in the background and dropping duplicated documents var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('createIndexExample1'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field db.createIndex('createIndexExample1', {a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
// A simple createIndex using a simple single field index var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('createIndexExample2'); // Insert a bunch of documents for the index collection.insert([{a:1}, {a:2}, {a:3}, {a:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.createIndex('a', {w:1}, function(err, indexName) { test.equal("a_1", indexName); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }); }); });
// A more complex createIndex using a compound unique index in the background var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('createIndexExample3'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); var options = {unique:true, background:true, w:1}; // Create an index on the a field collection.createIndex({a:1, b:1} , options, function(err, indexName) { test.ok(!options.readPreference); // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
-
distinct(key, query, options, callback){null}
-
The distinct command returns returns a list of distinct values for the given key across a collection.
Name Type Default Description key
string Field of the document to find distinct values for.
query
object The query for filtering the set of documents to which we apply the distinct filter.
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callback
Collection~resultCallback The command result callback
Examples
// Example of running the distinct command against a collection var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Crete the collection for the distinct example var collection = db.collection('distinctExample1'); // Insert documents to perform distinct against collection.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 field collection.distinct('a', function(err, docs) { test.deepEqual([0, 1, 2, 3], docs.sort()); // Perform a distinct query against the sub-field b.c collection.distinct('b.c', function(err, docs) { test.deepEqual(['a', 'b', 'c'], docs.sort()); db.close(); }); }); }); });
// Example of running the distinct command against a collection with a filter query var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Crete the collection for the distinct example var collection = db.collection('distinctExample2'); // Insert documents to perform distinct against collection.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 documents collection.distinct('a', {c:1}, function(err, docs) { test.deepEqual([5], docs.sort()); db.close(); }); }) });
-
drop(callback){null}
-
Drop the collection from the database, removing it permanently. New accesses will create a new collection.
Name Type Description callback
Collection~resultCallback The results callback
Example
// Example of a simple document save and then resave with safe set to true var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('test_other_drop'); // Drop the collection collection.drop(function(err, reply) { // Ensure we don't have the collection in the set of names db.listCollections(function(err, replies) { var found = false; // For each collection in the list of collection names in this db look for the // dropped collection replies.forEach(function(document) { if(document.name == "test_other_drop") { found = true; return; } }); // Ensure the collection is not found test.equal(false, found); // Let's close the db db.close(); }); }); });
-
dropAllIndexes(callback){null}
-
Drops all indexes from this collection.
Name Type Description callback
Collection~resultCallback The command result callback
Example
// Example of a simple document save and then resave with safe set to true var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { db.createCollection('dropExample1', function(err, r) { test.equal(null, err); // Drop the collection db.collection('dropExample1').dropAllIndexes(function(err, reply) { test.equal(null, err); // Let's close the db db.close(); }); }); });
-
dropIndex(indexName, options, callback){null}
-
Drops an index from this collection.
Name Type Default Description indexName
string Name of the index to drop.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~resultCallback The command result callback
Example
// An examples showing the creation and dropping of an index var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('dropIndexExample1'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Drop the index collection.dropIndex("a_1_b_1", function(err, result) { test.equal(null, err); // Verify that the index is gone collection.indexInformation(function(err, indexInformation) { test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); test.equal(null, indexInformation.a_1_b_1); db.close(); }); }); }); }); });
-
ensureIndex(fieldOrSpec, options, callback){null}
-
Ensures that an index exists, if it does not it creates it
Name Type Default Description fieldOrSpec
string | object Defines the index.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
unique
boolean false optional Creates an unique index.
sparse
boolean false optional Creates a sparse index.
background
boolean false optional Creates the index in the background, yielding whenever possible.
dropDups
boolean false optional A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
min
number null optional For geospatial indexes set the lower bound for the co-ordinates.
max
number null optional For geospatial indexes set the high bound for the co-ordinates.
v
number null optional Specify the format version of the indexes.
expireAfterSeconds
number null optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
number null optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
callback
Collection~resultCallback The command result callback
Examples
// A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('ensureIndexExample1'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field db.ensureIndex('ensureIndexExample1', {a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
// A more complex ensureIndex using a compound unique index in the background. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('ensureIndexExample2'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { test.equal(null, err); // Show that duplicate records got dropped collection.find({}).toArray(function(err, items) { test.equal(null, err); test.equal(4, items.length); // Peform a query, with explain to show we hit the query collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { test.equal(null, err); test.ok(explanation != null); db.close(); }); }) }); }); });
-
find(query){Cursor}
-
Creates a cursor for a query that can be used to iterate over results from MongoDB
Name Type Description query
object The cursor query object.
Throws:
MongoErrorExamples
// A simple query using the find method on the collection. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_query'); // Insert a bunch of documents for the testing collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) { test.equal(null, err); // Peform a simple find and return all the documents collection.find().toArray(function(err, docs) { test.equal(null, err); test.equal(3, docs.length); db.close(); }); }); });
// A simple query showing the explain for a query var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_explain_query'); // Insert a bunch of documents for the testing collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) { test.equal(null, err); // Peform a simple find and return all the documents collection.find({}, {explain:true}).toArray(function(err, docs) { test.equal(null, err); test.equal(1, docs.length); db.close(); }); }); });
// A simple query showing skip and limit var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_limit_skip_query'); // Insert a bunch of documents for the testing collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) { test.equal(null, err); // Peform a simple find and return all the documents collection.find({}, {skip:1, limit:1, fields:{b:1}}).toArray(function(err, docs) { test.equal(null, err); test.equal(1, docs.length); test.equal(null, docs[0].a); test.equal(2, docs[0].b); db.close(); }); }); });
-
findAndModify(query, sort, doc, options, callback){null}
-
Find and update a document.
Name Type Default Description query
object Query object to locate the object to modify.
sort
array 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 null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
remove
boolean false optional Set to true to remove the object before returning.
upsert
boolean false optional Perform an upsert operation.
new
boolean false optional Set to true if you want to return the modified object rather than the original. Ignored for remove.
fields
object null optional Object containing the field projection for the result returned from the operation.
callback
Collection~resultCallback The command result callback
Example
// 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. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_find_and_modify_operations_'); // Insert some test documentations collection.insert([{a:1}, {b:1}, {c:1}], {w:1}, function(err, result) { test.equal(null, err); // Simple findAndModify command returning the new document collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}, function(err, doc) { test.equal(null, err); test.equal(1, doc.value.a); test.equal(1, doc.value.b1); // Simple findAndModify command returning the new document and // removing it at the same time collection.findAndModify({b:1}, [['b', 1]], {$set:{b:2}}, {remove:true}, function(err, doc) { // Verify that the document is gone collection.findOne({b:1}, function(err, item) { test.equal(null, err); test.equal(null, item); // Simple findAndModify command performing an upsert and returning the new document // executing the command safely collection.findAndModify({d:1}, [['b', 1]], {d:1, f:1}, {new:true, upsert:true, w:1}, function(err, doc) { test.equal(null, err); test.equal(1, doc.value.d); test.equal(1, doc.value.f); db.close(); }) }); }); }); }); });
-
findAndRemove(query, sort, options, callback){null}
-
Find and remove a document.
Name Type Default Description query
object Query object to locate the object to modify.
sort
array If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~resultCallback The command result callback
Example
// An example of using findAndRemove var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_find_and_modify_operations_2'); // Insert some test documentations collection.insert([{a:1}, {b:1, d:1}, {c:1}], {w:1}, function(err, result) { test.equal(null, err); // Simple findAndModify command returning the old document and // removing it at the same time collection.findAndRemove({b:1}, [['b', 1]], function(err, doc) { test.equal(null, err); test.equal(1, doc.value.b); test.equal(1, doc.value.d); // Verify that the document is gone collection.findOne({b:1}, function(err, item) { test.equal(null, err); test.equal(null, item); db.close(); }); }); }); });
-
findOne(query, options, callback){null}
-
Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic operators and update instead for more efficient operations.
Name Type Default Description query
object Query for find Operation
options
object null optional Optional settings.
Name Type Default Description limit
number 0 optional Sets the limit of documents returned in the query.
sort
array | object null optional Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
fields
object null optional The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
skip
number 0 optional Set to skip N documents ahead in your query (useful for pagination).
hint
Object null optional Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
explain
boolean false optional Explain the query instead of returning the data.
snapshot
boolean false optional Snapshot query.
timeout
boolean false optional Specify if the cursor can timeout.
tailable
boolean false optional Specify if the cursor is tailable.
batchSize
number 0 optional Set the batchSize for the getMoreCommand when iterating over the query results.
returnKey
boolean false optional Only return the index key.
maxScan
number null optional Limit the number of items to scan.
min
number null optional Set index bounds.
max
number null optional Set index bounds.
showDiskLoc
boolean false optional Show disk location of results.
comment
string null optional You can put a $comment field on a query to make looking in the profiler logs simpler.
raw
boolean false optional Return all BSON documents as Raw Buffer documents.
readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
partial
boolean false optional Specify if the cursor should return partial results when querying against a sharded system
maxTimeMS
number null optional Number of miliseconds to wait before aborting the query.
callback
Collection~resultCallback The command result callback
Example
// A simple query using findOne var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_limit_skip_find_one_query'); // Insert a bunch of documents for the testing collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) { test.equal(null, err); // Peform a simple find and return all the documents collection.findOne({a:2}, {fields:{b:1}}, function(err, doc) { test.equal(null, err); test.equal(null, doc.a); test.equal(2, doc.b); db.close(); }); }); });
-
findOneAndDelete(filter, options, callback){null}
-
Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
Name Type Default Description filter
object Document selection filter.
options
object null optional Optional settings.
Name Type Default Description projection
object null optional Limits the fields to return for all matching documents.
sort
object null optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number null optional The maximum amount of time to allow the query to run.
callback
Collection~resultCallback The collection result callback
Example
// Example of a simple findOneAndDelete operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('find_one_and_delete'); col.insertMany([{a:1, b:1}], {w:1}, function(err, r) { test.equal(null, err); test.equal(1, r.result.n); col.findOneAndDelete({a:1} , { projection: {b:1}, sort: {a:1} } , function(err, r) { test.equal(null, err); test.equal(1, r.lastErrorObject.n); test.equal(1, r.value.b); db.close(); }); }); });
-
findOneAndReplace(filter, replacement, options, callback){null}
-
Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
Name Type Default Description filter
object Document selection filter.
replacement
object Document replacing the matching document.
options
object null optional Optional settings.
Name Type Default Description projection
object null optional Limits the fields to return for all matching documents.
sort
object null optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number null optional The maximum amount of time to allow the query to run.
upsert
boolean false optional Upsert the document if it does not exist.
returnOriginal
boolean true optional When false, returns the updated document rather than the original. The default is true.
callback
Collection~resultCallback The collection result callback
Example
// Example of a simple findOneAndReplace operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('find_one_and_replace'); col.insertMany([{a:1, b:1}], {w:1}, function(err, r) { test.equal(null, err); test.equal(1, r.result.n); col.findOneAndReplace({a:1} , {c:1, b:1} , { projection: {b:1, c:1} , sort: {a:1} , returnOriginal: false , upsert: true } , function(err, r) { test.equal(null, err); test.equal(1, r.lastErrorObject.n); test.equal(1, r.value.b); test.equal(1, r.value.c); db.close(); }); }); });
-
findOneAndUpdate(filter, update, options, callback){null}
-
Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
Name Type Default Description filter
object Document selection filter.
update
object Update operations to be performed on the document
options
object null optional Optional settings.
Name Type Default Description projection
object null optional Limits the fields to return for all matching documents.
sort
object null optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number null optional The maximum amount of time to allow the query to run.
upsert
boolean false optional Upsert the document if it does not exist.
returnOriginal
boolean true optional When false, returns the updated document rather than the original. The default is true.
callback
Collection~resultCallback The collection result callback
Example
// Example of a simple findOneAndUpdate operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('find_one_and_update'); col.insertMany([{a:1, b:1}], {w:1}, function(err, r) { test.equal(null, err); test.equal(1, r.result.n); col.findOneAndUpdate({a:1} , {$set: {d:1}} , { projection: {b:1, d:1} , sort: {a:1} , returnOriginal: false , upsert: true } , function(err, r) { test.equal(null, err); test.equal(1, r.lastErrorObject.n); test.equal(1, r.value.b); test.equal(1, r.value.d); db.close(); }); }); });
-
geoHaystackSearch(x, y, options, callback){null}
-
Execute a geo search using a geo haystack index on a collection.
Name Type Default Description 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
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxDistance
number null optional Include results up to maxDistance from the point.
search
object null optional Filter the results by a query.
limit
number false optional Max number of results to return.
callback
Collection~resultCallback The command result callback
Examples
// Example of a simple geoHaystackSearch query across some documents var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch the collection var collection = db.collection("simple_geo_haystack_command"); // Add a location based index collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}, function(err, result) { // Save a new location tagged document collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}, function(err, result) { // Use geoNear command to find document collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100}, function(err, docs) { test.equal(1, docs.results.length); db.close(); }); }); }); });
// A simple map reduce example var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection var collection = db.collection('test_map_reduce_functions'); // Insert some documents to perform map reduce over collection.insert([{'user_id':1}, {'user_id':2}], {w:1}, function(err, r) { // Map function var map = function() { emit(this.user_id, 1); }; // Reduce function var reduce = function(k,vals) { return 1; }; // Peform the map reduce collection.mapReduce(map, reduce, {out: {replace : 'tempCollection'}}, function(err, collection) { test.equal(null, err); // Mapreduce returns the temporary collection with the results collection.findOne({'_id':1}, function(err, result) { test.equal(1, result.value); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); db.close(); }); }); }); }); });
// A simple map reduce example using the inline output type on MongoDB > 1.7.6 returning the statistics var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection var collection = db.collection('test_map_reduce_functions_inline'); // Insert some test documents collection.insert([{'user_id':1}, {'user_id':2}], {w:1}, function(err, r) { // Map function var map = function() { emit(this.user_id, 1); }; // Reduce function var reduce = function(k,vals) { return 1; }; // Execute map reduce and return results inline collection.mapReduce(map, reduce, {out : {inline: 1}, verbose:true}, function(err, results, stats) { test.equal(2, results.length); test.ok(stats != null); collection.mapReduce(map, reduce, {out : {replace: 'mapreduce_integration_test'}, verbose:true}, function(err, results, stats) { test.ok(stats != null); db.close(); }); }); }); });
// Mapreduce different test with a provided scope containing a javascript function. var MongoClient = require('mongodb').MongoClient, Code = require('mongodb').Code, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection var collection = db.collection('test_map_reduce_functions_scope'); // Insert some test documents collection.insert([{'user_id':1, 'timestamp':new Date()} , {'user_id':2, 'timestamp':new Date()}], {w:1}, function(err, r) { // Map function var map = function(){ emit(fn(this.timestamp.getYear()), 1); } // Reduce function var reduce = function(k, v){ count = 0; for(i = 0; i < v.length; i++) { count += v[i]; } return count; } // Javascript function available in the map reduce scope var t = function(val){ return val+1; } // Execute the map reduce with the custom scope var o = {}; o.scope = { fn: new Code(t.toString()) } o.out = { replace: 'replacethiscollection' } collection.mapReduce(map, reduce, o, function(err, outCollection) { test.equal(null, err); // Find all entries in the map-reduce collection outCollection.find().toArray(function(err, results) { test.equal(null, err); test.equal(2, results[0].value) // mapReduce with scope containing plain function var o = {}; o.scope = { fn: t } o.out = { replace: 'replacethiscollection' } collection.mapReduce(map, reduce, o, function(err, outCollection) { test.equal(null, err); // Find all entries in the map-reduce collection outCollection.find().toArray(function(err, results) { test.equal(2, results[0].value) db.close(); }); }); }); }); }); });
// Mapreduce different test with a provided scope containing javascript objects with functions. var MongoClient = require('mongodb').MongoClient, Code = require('mongodb').Code, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection var collection = db.collection('test_map_reduce_functions_scope_objects'); // Insert some test documents collection.insert([{'user_id':1, 'timestamp':new Date()} , {'user_id':2, 'timestamp':new Date()}], {w:1}, function(err, r) { // Map function var map = function(){ emit(obj.fn(this.timestamp.getYear()), 1); } // Reduce function var reduce = function(k, v){ count = 0; for(i = 0; i < v.length; i++) { count += v[i]; } return count; } // Javascript function available in the map reduce scope var t = function(val){ return val+1; } // Execute the map reduce with the custom scope containing objects var o = {}; o.scope = { obj: {fn: new Code(t.toString())} } o.out = { replace: 'replacethiscollection' } collection.mapReduce(map, reduce, o, function(err, outCollection) { test.equal(null, err); // Find all entries in the map-reduce collection outCollection.find().toArray(function(err, results) { test.equal(null, err); test.equal(2, results[0].value) // mapReduce with scope containing plain function var o = {}; o.scope = { obj: {fn: t} } o.out = { replace: 'replacethiscollection' } collection.mapReduce(map, reduce, o, function(err, outCollection) { test.equal(null, err); // Find all entries in the map-reduce collection outCollection.find().toArray(function(err, results) { test.equal(2, results[0].value) db.close(); }); }); }); }); }); });
-
geoNear(x, y, options, callback){null}
-
Execute the geoNear command to search for items in the collection
Name Type Default Description 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
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
num
number null optional Max number of results to return.
minDistance
number null optional Include results starting at minDistance from a point (2.6 or higher)
maxDistance
number null optional Include results up to maxDistance from the point.
distanceMultiplier
number null optional Include a value to multiply the distances with allowing for range conversions.
query
object null optional Filter the results by a query.
spherical
boolean false optional Perform query using a spherical model.
uniqueDocs
boolean false optional The closest location in a document to the center of the search region will always be returned MongoDB > 2.X.
includeLocs
boolean false optional Include the location data fields in the top level of the results MongoDB > 2.X.
callback
Collection~resultCallback The command result callback
Example
// Example of a simple geoNear query across some documents var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch the collection var collection = db.collection("simple_geo_near_command"); // Add a location based index collection.ensureIndex({loc:"2d"}, function(err, result) { // Save a new location tagged document collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}, function(err, result) { // Use geoNear command to find document collection.geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) { test.equal(1, docs.results.length); db.close(); }); }); }); });
-
group(keys, condition, initial, reduce, finalize, command, options, callback){null}
-
Run a group command across a collection
Name Type Default Description keys
object | array | function | code An object, array or function expressing the keys to group by.
condition
object An optional condition that must be true for a row to be considered.
initial
object Initial value of the aggregation counter object.
reduce
function | Code The reduce function aggregates (reduces) the objects iterated
finalize
function | Code 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 null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
callback
Collection~resultCallback The command result callback
Example
// A whole lot of different wayt to execute the group command var MongoClient = require('mongodb').MongoClient, Code = require('mongodb').Code, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection var collection = db.collection('test_group'); // Peform a simple group by on an empty collection collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.deepEqual([], results); // Trigger some inserts on the collection collection.insert([{'a':2}, {'b':5}, {'a':1}], {w:1}, function(err, ids) { // Perform a group count collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.equal(3, results[0].count); // Pefrom a group count using the eval method collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", false, function(err, results) { test.equal(3, results[0].count); // Group with a conditional collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { // Results test.equal(1, results[0].count); // Group with a conditional using the EVAL method collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" , false, function(err, results) { // Results test.equal(1, results[0].count); // Insert some more test data collection.insert([{'a':2}, {'b':3}], {w:1}, function(err, ids) { // Do a Group by field a collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { // Results test.equal(2, results[0].a); test.equal(2, results[0].count); test.equal(null, results[1].a); test.equal(2, results[1].count); test.equal(1, results[2].a); test.equal(1, results[2].count); // Do a Group by field a collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; }, true, function(err, results) { // Results test.equal(2, results[0].a); test.equal(2, results[0].count); test.equal(null, results[1].a); test.equal(2, results[1].count); test.equal(1, results[2].a); test.equal(1, results[2].count); // Correctly handle illegal function collection.group([], {}, {}, "5 ++ 5", function(err, results) { test.ok(err.message != null); // Use a function to select the keys used to group by var keyf = 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) { // Results results.sort(function(a, b) { return b.count - a.count; }); test.equal(2, results[0].count); test.equal(2, results[0].a); test.equal(4, results[0].value); test.equal(1, results[1].count); test.equal(1, results[1].a); test.equal(1, results[1].value); // Use a Code object to select the keys used to group by var keyf = new Code(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) { // Results results.sort(function(a, b) { return b.count - a.count; }); test.equal(2, results[0].count); test.equal(2, results[0].a); test.equal(4, results[0].value); test.equal(1, results[1].count); test.equal(1, results[1].a); test.equal(1, results[1].value); // Correctly handle illegal function when using the EVAL method collection.group([], {}, {}, "5 ++ 5", false, function(err, results) { test.ok(err.message != null); db.close(); }); }); }); }); }); }); }); }); }); }); }); }); }); });
-
indexes(callback){null}
-
Retrieve all the indexes on the collection.
Name Type Description callback
Collection~resultCallback The command result callback
Example
// Example of retrieving a collections indexes var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Crete the collection for the distinct example var collection = db.collection('simple_key_based_distinct'); // Create a geo 2d index collection.ensureIndex({loc:"2d"}, {w:1}, function(err, result) { test.equal(null, err); // Create a simple single field index collection.ensureIndex({a:1}, {w:1}, function(err, result) { test.equal(null, err); setTimeout(function() { // List all of the indexes on the collection collection.indexes(function(err, indexes) { test.equal(3, indexes.length); db.close(); }); }, 1000); }); }); });
-
indexExists(indexes, callback){null}
-
Checks if one or more indexes exist on the collection, fails on first non-existing index
Name Type Description indexes
string | array One or more index names to check.
callback
Collection~resultCallback The command result callback
Example
// An example showing the use of the indexExists function for a single index name and a list of index names. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection that we are getting the options back from var collection = db.collection('test_collection_index_exists', {w:1}); test.equal(null, err); // Create an index on the collection collection.createIndex('a', {w:1}, function(err, indexName) { // Let's test to check if a single index exists collection.indexExists("a_1", function(err, result) { test.equal(true, result); // Let's test to check if multiple indexes are available collection.indexExists(["a_1", "_id_"], function(err, result) { test.equal(true, result); // Check if a non existing index exists collection.indexExists("c_1", function(err, result) { test.equal(false, result); db.close(); }); }); }); }); });
-
indexInformation(options, callback){null}
-
Retrieves this collections index info.
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description full
boolean false optional Returns the full raw index information.
callback
Collection~resultCallback The command result callback
Examples
// An example showing the information returned by indexInformation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('more_index_information_test_2'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Fetch basic indexInformation for collection db.indexInformation('more_index_information_test_2', function(err, indexInformation) { test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); // Fetch full index information collection.indexInformation({full:true}, function(err, indexInformation) { test.deepEqual({ _id: 1 }, indexInformation[0].key); test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); db.close(); }); }); }); }); });
// An examples showing the information returned by indexInformation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('more_index_information_test_3'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { test.equal(null, err); // Fetch basic indexInformation for collection collection.indexInformation(function(err, indexInformation) { test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); // Fetch full index information collection.indexInformation({full:true}, function(err, indexInformation) { test.deepEqual({ _id: 1 }, indexInformation[0].key); test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); db.close(); }); }); }); }); });
-
initializeOrderedBulkOp(options, callback){null}
-
Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
OrderedBulkOperation The command result callback
-
initializeUnorderedBulkOp(options, callback){null}
-
Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
UnorderedBulkOperation The command result callback
-
insert(docs, options, callback){null}
-
Inserts a single document or a an array of documents into MongoDB.
Name Type Default Description docs
object | Array.<object> Documents to insert.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
serializeFunctions
boolean false optional Serialize functions on any object.
forceServerObjectId
boolean false optional Force server to assign _id values instead of driver.
callback
Collection~writeOpCallback The command result callback
- Deprecated
- Yes
Examples
// A simple document insert example, not using safe mode to ensure document persistance on MongoDB var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection("simple_document_insert_collection_no_safe"); // Insert a single document collection.insert({hello:'world_no_safe'}); // Wait for a second before finishing up, to ensure we have written the item to disk setTimeout(function() { // Fetch the document collection.findOne({hello:'world_no_safe'}, function(err, item) { test.equal(null, err); test.equal('world_no_safe', item.hello); db.close(); }) }, 100); });
// A batch document insert example, using safe mode to ensure document persistance on MongoDB var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch a collection to insert document into var collection = db.collection("batch_document_insert_collection_safe"); // Insert a single document collection.insert([{hello:'world_safe1'} , {hello:'world_safe2'}], {w:1}, function(err, result) { test.equal(null, err); // Fetch the document collection.findOne({hello:'world_safe2'}, function(err, item) { test.equal(null, err); test.equal('world_safe2', item.hello); db.close(); }) }); });
// Example of inserting a document containing functions var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch a collection to insert document into var collection = db.collection("simple_document_insert_with_function_safe"); var o = {w:1}; o.serializeFunctions = true; // Insert a single document collection.insert({hello:'world' , func:function() {}}, o, function(err, result) { test.equal(null, err); // Fetch the document collection.findOne({hello:'world'}, function(err, item) { test.equal(null, err); test.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 var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection var collection = db.collection('keepGoingExample'); // Add an unique index to title to force errors in the batch insert collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) { // Insert some intial data into the collection collection.insert([{name:"Jim"} , {name:"Sarah", title:"Princess"}], {w:1}, function(err, result) { // Force keep going flag, ignoring unique index issue collection.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) { test.equal(3, count); }) }); }); }); });
-
insertMany(docs, options, callback){null}
-
Inserts an array of documents into MongoDB.
Name Type Default Description docs
Array.<object> Documents to insert.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
serializeFunctions
boolean false optional Serialize functions on any object.
forceServerObjectId
boolean false optional Force server to assign _id values instead of driver.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple insertMany operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('insert_many'); col.insertMany([{a:1}, {a:2}], function(err, r) { test.equal(null, err); test.equal(2, r.insertedCount); // Finish up test db.close(); }); });
-
insertOne(doc, options, callback){null}
-
Inserts a single document into MongoDB.
Name Type Default Description doc
object Document to insert.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
serializeFunctions
boolean false optional Serialize functions on any object.
forceServerObjectId
boolean false optional Force server to assign _id values instead of driver.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple insertOne operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('insert_one'); col.insertOne({a:1}, function(err, r) { test.equal(null, err); test.equal(1, r.insertedCount); // Finish up test db.close(); }); });
-
isCapped(callback){null}
-
Returns if the collection is a capped collection
Name Type Description callback
Collection~resultCallback The results callback
Example
// An example showing how to establish if it's a capped collection var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection that we are getting the options back from db.createCollection('test_collection_is_capped', {'capped':true, 'size':1024}, function(err, collection) { test.equal('test_collection_is_capped', collection.collectionName); // Let's fetch the collection options collection.isCapped(function(err, capped) { test.equal(true, capped); db.close(); }); }); });
-
mapReduce(map, reduce, options, callback){null}
-
Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
Name Type Default Description map
function | string The mapping function.
reduce
function | string The reduce function.
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
out
object null optional Sets the output target for the map reduce job. {inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}
query
object null optional Query filter object.
sort
object null optional Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
limit
number null optional Number of objects to return from collection.
keeptemp
boolean false optional Keep temporary data.
finalize
function | string null optional Finalize function.
scope
object null optional Can pass in variables that can be access from map/reduce/finalize.
jsMode
boolean false optional It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
verbose
boolean false optional Provide statistics on job execution time.
callback
Collection~resultCallback The command result callback
Throws:
MongoError -
options(callback){null}
-
Returns the options of the collection.
Name Type Description callback
Collection~resultCallback The results callback
Example
// An example returning the options for a collection. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a test collection that we are getting the options back from db.createCollection('test_collection_options', {'capped':true, 'size':1024}, function(err, collection) { test.equal('test_collection_options', collection.collectionName); // Let's fetch the collection options collection.options(function(err, options) { test.equal(true, options.capped); test.ok(options.size >= 1024); db.close(); }); }); });
-
parallelCollectionScan(pipeline, options, callback){null}
-
Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are no ordering guarantees for returned results.
Name Type Default Description pipeline
object Array containing all the aggregation framework commands for the execution.
options
object null optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string null optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
batchSize
number null optional Set the batchSize for the getMoreCommand when iterating over the query results.
numCursors
number 1 optional The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
callback
Collection~parallelCollectionScanCallback The command result callback
Example
// A parallelCollectionScan example var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var docs = []; // Insert some documents for(var i = 0; i < 1000; i++) { docs.push({a:i}); } // Get the collection var collection = db.collection('parallelCollectionScan'); // Insert 1000 documents in a batch collection.insert(docs, function(err, result) { var results = []; var numCursors = 3; // Execute parallelCollectionScan command collection.parallelCollectionScan({numCursors:numCursors}, function(err, cursors) { test.equal(null, err); test.ok(cursors != null); test.ok(cursors.length > 0); for(var i = 0; i < cursors.length; i++) { cursors[i].toArray(function(err, items) { test.equal(err, null); // Add docs to results array results = results.concat(items); numCursors = numCursors - 1; // No more cursors let's ensure we got all results if(numCursors == 0) { test.equal(docs.length, results.length); db.close(); } }); } }); }); });
-
reIndex(callback){null}
-
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.
Name Type Description callback
Collection~resultCallback The command result callback
Example
// An example showing how to force a reindex of a collection. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('shouldCorrectlyForceReindexOnCollection'); // Insert a bunch of documents for the index collection.insert([{a:1, b:1} , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}, function(err, result) { test.equal(null, err); // Create an index on the a field collection.ensureIndex({a:1, b:1} , {unique:true, background:true, w:1}, function(err, indexName) { // Force a reindex of the collection collection.reIndex(function(err, result) { test.equal(null, err); test.equal(true, result); // Verify that the index is gone collection.indexInformation(function(err, indexInformation) { test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); db.close(); }); }); }); }); });
-
remove(selector, options, callback){null}
-
Remove documents.
Name Type Default Description selector
object The selector for the update operation.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
single
boolean false optional Removes the first document found.
callback
Collection~writeOpCallback The command result callback
- Deprecated
- Yes
Examples
// An example removing all documents in a collection not using safe mode var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch a collection to insert document into var collection = db.collection("remove_all_documents_no_safe"); // Insert a bunch of documents collection.insert([{a:1}, {b:2}], {w:1}, function(err, result) { test.equal(null, err); // Remove all the document collection.remove(); // Fetch all results collection.find().toArray(function(err, items) { test.equal(null, err); test.equal(0, items.length); db.close(); }); }) });
// An example removing a subset of documents using safe mode to ensure removal of documents var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { test.equal(null, err); // Fetch a collection to insert document into var collection = db.collection("remove_subset_of_documents_safe"); // Insert a bunch of documents collection.insert([{a:1}, {b:2}], {w:1}, function(err, result) { test.equal(null, err); // Remove all the document collection.remove({a:1}, {w:1}, function(err, r) { test.equal(null, err); test.equal(1, r.result.n); db.close(); }); }); });
-
removeMany(filter, options, callback){null}
-
Remove multiple documents on MongoDB
Name Type Default Description filter
object The Filter used to select the documents to remove
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple removeMany operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('remove_many'); col.insertMany([{a:1}, {a:1}], function(err, r) { test.equal(null, err); test.equal(2, r.insertedCount); // Update all documents col.removeMany({a:1}, function(err, r) { test.equal(null, err); test.equal(2, r.deletedCount); // Finish up test db.close(); }); }); });
-
removeOne(filter, options, callback){null}
-
Remove a document on MongoDB
Name Type Default Description filter
object The Filter used to select the document to remove
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple removeOne operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('remove_one'); col.insertMany([{a:1}, {a:1}], function(err, r) { test.equal(null, err); test.equal(2, r.insertedCount); col.removeOne({a:1}, function(err, r) { test.equal(null, err); test.equal(1, r.deletedCount); // Finish up test db.close(); }); }); });
-
rename(newName, options, callback){null}
-
Rename the collection.
Name Type Default Description newName
string New name of of the collection.
options
object null optional Optional settings.
Name Type Default Description dropTarget
boolean false optional Drop the target name collection if it previously exists.
callback
Collection~collectionResultCallback The results callback
Example
// An example of illegal and legal renaming of a collection var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Open a couple of collections db.createCollection('test_rename_collection', function(err, collection1) { db.createCollection('test_rename_collection2', function(err, collection2) { // Attemp to rename a collection to a number try { collection1.rename(5, function(err, collection) {}); } catch(err) { test.ok(err instanceof Error); test.equal("collection name must be a String", err.message); } // Attemp to rename a collection to an empty string try { collection1.rename("", function(err, collection) {}); } catch(err) { test.ok(err instanceof Error); test.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) { test.ok(err instanceof Error); test.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) { test.ok(err instanceof Error); test.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) { test.ok(err instanceof Error); test.equal("collection names must not start or end with '.'", err.message); } // Attemp to rename a collection to an illegal name with an empty middle name try { collection1.rename("tes..t", function(err, collection) {}); } catch(err) { test.equal("collection names cannot be empty", err.message); } // Insert a couple of documents collection1.insert([{'x':1}, {'x':2}], {w:1}, function(err, docs) { // Attemp to rename the first collection to the second one, this will fail collection1.rename('test_rename_collection2', function(err, collection) { test.ok(err instanceof Error); test.ok(err.message.length > 0); // Attemp to rename the first collection to a name that does not exist // this will be succesful collection1.rename('test_rename_collection3', function(err, collection2) { test.equal("test_rename_collection3", collection2.collectionName); // Ensure that the collection is pointing to the new one collection2.count(function(err, count) { test.equal(2, count); db.close(); }); }); }); }); }); }); });
-
replaceOne(filter, doc, options, callback){null}
-
Replace a document on MongoDB
Name Type Default Description filter
object The Filter used to select the document to update
doc
object The Document that replaces the matching document
options
object null optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
-
save(doc, options, callback){null}
-
Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic operators and update instead for more efficient operations.
Name Type Default Description doc
object Document to save
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
Examples
// Example of a simple document save with safe set to false var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch the collection var collection = db.collection("save_a_simple_document"); // Save a document with no safe option collection.save({hello:'world'}); // Wait for a second setTimeout(function() { // Find the saved document collection.findOne({hello:'world'}, function(err, item) { test.equal(null, err); test.equal('world', item.hello); db.close(); }); }, 2000); });
// Example of a simple document save and then resave with safe set to true var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Fetch the collection var collection = db.collection("save_a_simple_document_modify_it_and_resave_it"); // Save a document with no safe option collection.save({hello:'world'}, {w:1}, function(err, result) { // Find the saved document collection.findOne({hello:'world'}, function(err, item) { test.equal(null, err); test.equal('world', item.hello); // Update the document item['hello2'] = 'world2'; // Save the item with the additional field collection.save(item, {w:1}, function(err, result) { // Find the changed document collection.findOne({hello:'world'}, function(err, item) { test.equal(null, err); test.equal('world', item.hello); test.equal('world2', item.hello2); db.close(); }); }); }); }); });
-
stats(options, callback){null}
-
Get all the collection statistics.
Name Type Default Description options
object null optional Optional settings.
Name Type Default Description scale
number null optional Divide the returned sizes by scale value.
callback
Collection~resultCallback The collection result callback
Example
// Example of retrieving a collections stats var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Crete the collection for the distinct example var collection = db.collection('collection_stats_test'); // Insert some documents collection.insert([{a:1}, {hello:'world'}], {w:1}, function(err, result) { // Retrieve the statistics for the collection collection.stats(function(err, stats) { test.equal(2, stats.count); db.close(); }); }); });
-
update(selector, document, options, callback){null}
-
Updates documents.
Name Type Default Description selector
object The selector for the update operation.
document
object The update document.
options
object null optional Optional settings.
Name Type Default Description w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
upsert
boolean false optional Update operation is an upsert.
multi
boolean false optional Update one/all documents with operation.
callback
Collection~writeOpCallback The command result callback
- Deprecated
- Yes
Throws:
MongoErrorExamples
// Example of a simple document update with safe set to false on an existing document var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get a collection var collection = db.collection('update_a_simple_document'); // Insert a document, then update it collection.insert({a:1}, {w:1}, function(err, doc) { // Update the document with an atomic operator collection.update({a:1}, {$set:{b:2}}); // Wait for a second then fetch the document setTimeout(function() { // Fetch the document that we modified collection.findOne({a:1}, function(err, item) { test.equal(null, err); test.equal(1, item.a); test.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) var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get a collection var collection = db.collection('update_a_simple_document_upsert'); // Update the document using an upsert operation, ensuring creation if it does not exist collection.update({a:1}, {b:2, a:1}, {upsert:true, w: 1}, function(err, result) { test.equal(null, err); test.equal(1, result.result.n); // Fetch the document that we modified and check if it got inserted correctly collection.findOne({a:1}, function(err, item) { test.equal(null, err); test.equal(1, item.a); test.equal(2, item.b); db.close(); }); }); });
// Example of an update across multiple documents using the multi option. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get a collection var collection = db.collection('update_a_simple_document_multi'); // Insert a couple of documentations collection.insert([{a:1, b:1}, {a:1, b:2}], {w:1}, function(err, result) { var o = {w:1}; o.multi = true // Update multiple documents using the multi option collection.update({a:1}, {$set:{b:0}}, o, function(err, r) { test.equal(null, err); test.equal(2, r.result.n); // Fetch all the documents and verify that we have changed the b value collection.find().toArray(function(err, items) { test.equal(null, err); test.equal(1, items[0].a); test.equal(0, items[0].b); test.equal(1, items[1].a); test.equal(0, items[1].b); db.close(); }); }) }); });
-
updateMany(filter, update, options, callback){null}
-
Update multiple documents on MongoDB
Name Type Default Description filter
object The Filter used to select the document to update
update
object The update operations to be applied to the document
options
object null optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple updateMany operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('update_many'); col.insertMany([{a:1}, {a:1}], function(err, r) { test.equal(null, err); test.equal(2, r.insertedCount); // Update all documents col.updateMany({a:1}, {$set: {b: 1}}, function(err, r) { test.equal(null, err); test.equal(2, r.matchedCount); test.equal(2, r.modifiedCount); // Finish up test db.close(); }); }); });
-
updateOne(filter, update, options, callback){null}
-
Update a single document on MongoDB
Name Type Default Description filter
object The Filter used to select the document to update
update
object The update operations to be applied to the document
options
object null optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string null optional The write concern.
wtimeout
number null optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
callback
Collection~writeOpCallback The command result callback
Example
// Example of a simple updateOne operation var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Get the collection var col = db.collection('update_one'); col.updateOne({a:1} , {$set: {a:2}} , {upsert:true}, function(err, r) { test.equal(null, err); test.equal(1, r.matchedCount); test.equal(1, r.upsertedCount); // Finish up test db.close(); }); });
Type Definitions
-
collectionResultCallback(error, collection)
-
The callback format for the collection method, must be used if strict is specified
Name Type Description error
MongoError An error instance representing the error during the execution.
collection
Collection The collection instance.
-
countCallback(error, result)
-
The callback format for results
Name Type Description error
MongoError An error instance representing the error during the execution.
result
number The count of documents that matched the query.
-
parallelCollectionScanCallback(error, cursors)
-
The callback format for results
Name Type Description error
MongoError An error instance representing the error during the execution.
cursors
Array.<Cursor> A list of cursors returned allowing for parallel reading of collection.
-
resultCallback(error, result)
-
The callback format for results
Name Type Description error
MongoError An error instance representing the error during the execution.
result
object The result object if the command was executed successfully.
-
writeOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~WriteOpResult The result object if the command was executed successfully.
-
WriteOpResultObject
-
Properties:
Name Type Description ops
Array.<object> All the documents inserted with their new _id values if forceServerObjectId == false.
connection
object The connection object used for the operation.
result
object The command result object.