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. |
readConcern |
object | The current read 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 [] optional Array containing all the aggregation framework commands for the execution.
options
object optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
cursor
object 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 Description batchSize
number 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 >).
maxTimeMS
number optional maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
raw
boolean false optional Return document results as raw BSON buffers.
promoteLongs
boolean true optional Promotes Long values to number if they fit inside the 53 bits resolution.
promoteValues
boolean true optional Promotes BSON values to native types where possible, set to false to only receive wrapper types.
promoteBuffers
boolean false optional Promotes Binary BSON values to native Node Buffers.
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
comment
string optional Add a comment to an aggregation command
hint
string | object optional Add an index selection hint to an aggregation command
session
ClientSession optional optional session to use for this operation
callback
Collection~aggregationCallback The command result callback
-
bulkWrite(operations, options, callback){Promise}
-
Perform a bulkWrite operation without a fluent API
Legal operation types are
{ insertOne: { document: { a: 1 } } }
{ updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
{ updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
{ deleteOne: { filter: {c:1} } }
{ deleteMany: { filter: {c:1} } }
{ replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
If documents passed in do not contain the _id field,
one will be added to each of the documents missing it by the driver, mutating the document. This behavior
can be overridden by setting the forceServerObjectId flag.Name Type Description operations
Array.<object> Bulk operations to perform.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
serializeFunctions
boolean false optional Serialize functions on any object.
ordered
boolean true optional Execute write operation in ordered or unordered fashion.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
session
ClientSession optional optional session to use for this operation
callback
Collection~bulkWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
count(query, options, callback){Promise}
-
An estimated count of matching documents in the db to a query.
NOTE: This method has been deprecated, since it does not provide an accurate count of the documents
in a collection. To obtain an accurate count of documents in the collection, usecountDocuments
.
To obtain an estimated count of all documents in the collection, useestimatedDocumentCount
.Name Type Default Description query
object {} optional The query for the count.
options
object optional Optional settings.
Name Type Description limit
boolean optional The limit of documents to count.
skip
boolean optional The number of documents to skip for the count.
hint
string optional An index name hint for the query.
readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxTimeMS
number optional Number of miliseconds to wait before aborting the query.
session
ClientSession optional optional session to use for this operation
callback
Collection~countCallback optional The command result callback
- Deprecated
- use
countDocuments
orestimatedDocumentCount
instead
- use
Returns:
Promise if no callback passed
-
countDocuments(query, options, callback){Promise}
-
Gets the number of documents matching the filter.
Note: When migrating from
count
tocountDocuments
the following query operators must be replaced:Operator Replacement $where
$expr
$near
$geoWithin
with$center
$nearSphere
$geoWithin
with$centerSphere
Name Type Description query
object optional the query for the count
options
object optional Optional settings.
Name Type Description collation
object optional Specifies a collation.
hint
string | object optional The index to use.
limit
number optional The maximum number of document to count.
maxTimeMS
number optional The maximum amount of time to allow the operation to run.
skip
number optional The number of documents to skip before counting.
callback
Collection~countCallback optional The command result callback.
- See:
-
- https://www.mongodb.com/docs/manual/reference/operator/query/expr/
- https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
- https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
- https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
Returns:
Promise if no callback passed.
-
createIndex(fieldOrSpec, options, callback){Promise}
-
Creates an index on the db and collection collection.
Name Type Description fieldOrSpec
string | object Defines the index.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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 optional For geospatial indexes set the lower bound for the co-ordinates.
max
number optional For geospatial indexes set the high bound for the co-ordinates.
v
number optional Specify the format version of the indexes.
expireAfterSeconds
number optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
string optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
partialFilterExpression
object optional Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
createIndexes(indexSpecs, options, callback){Promise}
-
Creates multiple indexes in the collection, this method is only supported for
MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
error. Index specifications are defined at https://www.mongodb.com/docs/manual/reference/command/createIndexes/.Name Type Description indexSpecs
array An array of index specifications to be created
options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
deleteMany(filter, options, callback){Promise}
-
Delete multiple documents from a collection
Name Type Description filter
object The Filter used to select the documents to remove
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
callback
Collection~deleteWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
deleteOne(filter, options, callback){Promise}
-
Delete a document from a collection
Name Type Description filter
object The Filter used to select the document to remove
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
callback
Collection~deleteWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
distinct(key, query, options, callback){Promise}
-
The distinct command returns returns a list of distinct values for the given key across a collection.
Name Type 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 optional Optional settings.
Name Type Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxTimeMS
number optional Number of miliseconds to wait before aborting the query.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
drop(options, callback){Promise}
-
Drop the collection from the database, removing it permanently. New accesses will create a new collection.
Name Type Description options
object optional Optional settings.
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The results callback
Returns:
Promise if no callback passed
-
dropAllIndexes(callback){Promise}
-
Drops all indexes from this collection.
Name Type Description callback
Collection~resultCallback The command result callback
- Deprecated
- use dropIndexes
Returns:
Promise if no [callback] passed
-
dropIndex(indexName, options, callback){Promise}
-
Drops an index from this collection.
Name Type Description indexName
string Name of the index to drop.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
maxTimeMS
number optional Number of miliseconds to wait before aborting the query.
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
dropIndexes(options, callback){Promise}
-
Drops all indexes from this collection.
Name Type Description options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
maxTimeMS
number optional Number of miliseconds to wait before aborting the query.
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
ensureIndex(fieldOrSpec, options, callback){Promise}
-
Ensures that an index exists, if it does not it creates it
Name Type Description fieldOrSpec
string | object Defines the index.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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 optional For geospatial indexes set the lower bound for the co-ordinates.
max
number optional For geospatial indexes set the high bound for the co-ordinates.
v
number optional Specify the format version of the indexes.
expireAfterSeconds
number optional Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
name
number optional Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
- Deprecated
- use createIndexes instead
Returns:
Promise if no callback passed
-
estimatedDocumentCount(options, callback){Promise}
-
Gets an estimate of the count of documents in a collection using collection metadata.
Name Type Description options
object optional Optional settings.
Name Type Description maxTimeMS
number optional The maximum amount of time to allow the operation to run.
callback
Collection~countCallback optional The command result callback.
Returns:
Promise if no callback passed.
-
find(query, options){Cursor}
-
Creates a cursor for a query that can be used to iterate over results from MongoDB
Name Type Default Description query
object {} optional The cursor query object.
options
object optional Optional settings.
Name Type Default Description limit
number 0 optional Sets the limit of documents returned in the query.
sort
array | object optional Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
projection
object optional The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
fields
object optional Deprecated Use
options.projection
insteadskip
number 0 optional Set to skip N documents ahead in your query (useful for pagination).
hint
Object 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 DEPRECATED: 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 optional DEPRECATED: Limit the number of items to scan.
min
number optional Set index bounds.
max
number optional Set index bounds.
showDiskLoc
boolean false optional Show disk location of results.
comment
string optional You can put a $comment field on a query to make looking in the profiler logs simpler.
raw
boolean false optional Return document results as raw BSON buffers.
promoteLongs
boolean true optional Promotes Long values to number if they fit inside the 53 bits resolution.
promoteValues
boolean true optional Promotes BSON values to native types where possible, set to false to only receive wrapper types.
promoteBuffers
boolean false optional Promotes Binary BSON values to native Node Buffers.
readPreference
ReadPreference | string 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 optional Number of miliseconds to wait before aborting the query.
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
session
ClientSession optional optional session to use for this operation
Throws:
-
findAndModify(query, sort, doc, options, callback){Promise}
-
Find and update a document.
Name Type 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 optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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.
projection
object optional Object containing the field projection for the result returned from the operation.
fields
object optional Deprecated Use
options.projection
insteadsession
ClientSession optional optional session to use for this operation
arrayFilters
Array optional optional list of array filters referenced in filtered positional operators
callback
Collection~findAndModifyCallback optional The command result callback
- Deprecated
- use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
Returns:
Promise if no callback passed
-
findAndRemove(query, sort, options, callback){Promise}
-
Find and remove a document.
Name Type 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 optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
- Deprecated
- use findOneAndDelete instead
Returns:
Promise if no callback passed
-
findOne(query, options, callback){Promise}
-
Fetches the first document that matches the query
Name Type Description query
object Query for find Operation
options
object optional Optional settings.
Name Type Default Description limit
number 0 optional Sets the limit of documents returned in the query.
sort
array | object optional Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
projection
object optional The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
fields
object optional Deprecated Use
options.projection
insteadskip
number 0 optional Set to skip N documents ahead in your query (useful for pagination).
hint
Object 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 DEPRECATED: 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 optional DEPRECATED: Limit the number of items to scan.
min
number optional Set index bounds.
max
number optional Set index bounds.
showDiskLoc
boolean false optional Show disk location of results.
comment
string optional You can put a $comment field on a query to make looking in the profiler logs simpler.
raw
boolean false optional Return document results as raw BSON buffers.
promoteLongs
boolean true optional Promotes Long values to number if they fit inside the 53 bits resolution.
promoteValues
boolean true optional Promotes BSON values to native types where possible, set to false to only receive wrapper types.
promoteBuffers
boolean false optional Promotes Binary BSON values to native Node Buffers.
readPreference
ReadPreference | string 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 optional Number of miliseconds to wait before aborting the query.
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
findOneAndDelete(filter, options, callback){Promise.<Collection~findAndModifyWriteOpResultObject>}
-
Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
Name Type Description filter
object The Filter used to select the document to remove
options
object optional Optional settings.
Name Type Description projection
object optional Limits the fields to return for all matching documents.
sort
object optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number optional The maximum amount of time to allow the query to run.
session
ClientSession optional optional session to use for this operation
callback
Collection~findAndModifyCallback optional The collection result callback
Returns:
Promise if no callback passed
-
findOneAndReplace(filter, replacement, options, callback){Promise.<Collection~findAndModifyWriteOpResultObject>}
-
Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
Name Type Description filter
object The Filter used to select the document to replace
replacement
object The Document that replaces the matching document
options
object optional Optional settings.
Name Type Default Description projection
object optional Limits the fields to return for all matching documents.
sort
object optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number 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.
session
ClientSession optional optional session to use for this operation
callback
Collection~findAndModifyCallback optional The collection result callback
Returns:
Promise if no callback passed
-
findOneAndUpdate(filter, update, options, callback){Promise.<Collection~findAndModifyWriteOpResultObject>}
-
Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
Name Type Description filter
object The Filter used to select the document to update
update
object Update operations to be performed on the document
options
object optional Optional settings.
Name Type Default Description projection
object optional Limits the fields to return for all matching documents.
sort
object optional Determines which document the operation modifies if the query selects multiple documents.
maxTimeMS
number 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.
session
ClientSession optional optional session to use for this operation
arrayFilters
Array optional optional list of array filters referenced in filtered positional operators
callback
Collection~findAndModifyCallback optional The collection result callback
Returns:
Promise if no callback passed
-
geoHaystackSearch(x, y, options, callback){Promise}
-
Execute a geo search using a geo haystack index on a collection.
Name Type 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 optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
maxDistance
number optional Include results up to maxDistance from the point.
search
object optional Filter the results by a query.
limit
number false optional Max number of results to return.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
group(keys, condition, initial, reduce, finalize, command, options, callback){Promise}
-
Run a group command across a collection
Name Type 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 optional Optional settings.
Name Type Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
- Deprecated
- MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.
Returns:
Promise if no callback passed
-
indexes(options, callback){Promise}
-
Retrieve all the indexes on the collection.
Name Type Description options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
indexExists(indexes, options, callback){Promise}
-
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.
options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
indexInformation(options, callback){Promise}
-
Retrieves this collections index info.
Name Type Description options
object optional Optional settings.
Name Type Default Description full
boolean false optional Returns the full raw index information.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
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 Description options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
ignoreUndefined
boolean false optional Specify if the BSON serializer should ignore undefined fields.
callback
OrderedBulkOperation The command result callback
-
initializeUnorderedBulkOp(options){UnorderedBulkOperation}
-
Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Name Type Description options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
ignoreUndefined
boolean false optional Specify if the BSON serializer should ignore undefined fields.
session
ClientSession optional optional session to use for this operation
-
insert(docs, options, callback){Promise}
-
Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the _id field,
one will be added to each of the documents missing it by the driver, mutating the document. This behavior
can be overridden by setting the forceServerObjectId flag.Name Type Description docs
object | Array.<object> Documents to insert.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
session
ClientSession optional optional session to use for this operation
callback
Collection~insertWriteOpCallback optional The command result callback
- Deprecated
- Use insertOne, insertMany or bulkWrite
Returns:
Promise if no callback passed
-
insertMany(docs, options, callback){Promise}
-
Inserts an array of documents into MongoDB. If documents passed in do not contain the _id field,
one will be added to each of the documents missing it by the driver, mutating the document. This behavior
can be overridden by setting the forceServerObjectId flag.Name Type Description docs
Array.<object> Documents to insert.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
ordered
boolean true optional If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
session
ClientSession optional optional session to use for this operation
callback
Collection~insertWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
insertOne(doc, options, callback){Promise}
-
Inserts a single document into MongoDB. If documents passed in do not contain the _id field,
one will be added to each of the documents missing it by the driver, mutating the document. This behavior
can be overridden by setting the forceServerObjectId flag.Name Type Description doc
object Document to insert.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
session
ClientSession optional optional session to use for this operation
callback
Collection~insertOneWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
isCapped(options, callback){Promise}
-
Returns if the collection is a capped collection
Name Type Description options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The results callback
Returns:
Promise if no callback passed
-
listIndexes(options){CommandCursor}
-
Get the list of all indexes information for the collection.
Name Type Description options
object optional Optional settings.
Name Type Description batchSize
number optional The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
session
ClientSession optional optional session to use for this operation
-
mapReduce(map, reduce, options, callback){Promise}
-
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 Description map
function | string The mapping function.
reduce
function | string The reduce function.
options
object optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
out
object optional Sets the output target for the map reduce job. {inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}
query
object optional Query filter object.
sort
object optional Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
limit
number optional Number of objects to return from collection.
keeptemp
boolean false optional Keep temporary data.
finalize
function | string optional Finalize function.
scope
object 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.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Throws:
Returns:
Promise if no callback passed
-
options(options, callback){Promise}
-
Returns the options of the collection.
Name Type Description options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The results callback
Returns:
Promise if no callback passed
-
parallelCollectionScan(options, callback){Promise}
-
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 Description options
object optional Optional settings.
Name Type Default Description readPreference
ReadPreference | string optional The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
batchSize
number 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)
raw
boolean false optional Return all BSON documents as Raw Buffer documents.
callback
Collection~parallelCollectionScanCallback optional The command result callback
Returns:
Promise if no callback passed
-
reIndex(options, callback){Promise}
-
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 options
Object optional Optional settings
Name Type Description session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The command result callback
Returns:
Promise if no callback passed
-
remove(selector, options, callback){Promise}
-
Remove documents.
Name Type Description selector
object The selector for the update operation.
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
single
boolean false optional Removes the first document found.
session
ClientSession optional optional session to use for this operation
callback
Collection~writeOpCallback optional The command result callback
- Deprecated
- use deleteOne, deleteMany or bulkWrite
Returns:
Promise if no callback passed
-
rename(newName, options, callback){Promise}
-
Rename the collection.
Name Type Description newName
string New name of of the collection.
options
object optional Optional settings.
Name Type Default Description dropTarget
boolean false optional Drop the target name collection if it previously exists.
session
ClientSession optional optional session to use for this operation
callback
Collection~collectionResultCallback optional The results callback
Returns:
Promise if no callback passed
-
replaceOne(filter, doc, options, callback){Promise.<Collection~updatewriteOpResultObject>}
-
Replace a document in a collection with another document
Name Type Description filter
object The Filter used to select the document to replace
doc
object The Document that replaces the matching document
options
object optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
session
ClientSession optional optional session to use for this operation
callback
Collection~updateWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
save(doc, options, callback){Promise}
-
Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
operators and update instead for more efficient operations.Name Type Description doc
object Document to save
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
session
ClientSession optional optional session to use for this operation
callback
Collection~writeOpCallback optional The command result callback
- Deprecated
- use insertOne, insertMany, updateOne or updateMany
Returns:
Promise if no callback passed
-
stats(options, callback){Promise}
-
Get all the collection statistics.
Name Type Description options
object optional Optional settings.
Name Type Description scale
number optional Divide the returned sizes by scale value.
session
ClientSession optional optional session to use for this operation
callback
Collection~resultCallback optional The collection result callback
Returns:
Promise if no callback passed
-
update(selector, update, options, callback){Promise}
-
Updates documents.
Name Type Description selector
object The selector for the update operation.
update
object The update operations to be applied to the documents
options
object optional Optional settings.
Name Type Default Description w
number | string optional The write concern.
wtimeout
number 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.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
collation
object optional Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
arrayFilters
Array optional optional list of array filters referenced in filtered positional operators
session
ClientSession optional optional session to use for this operation
callback
Collection~writeOpCallback optional The command result callback
- Deprecated
- use updateOne, updateMany or bulkWrite
Throws:
Returns:
Promise if no callback passed
-
updateMany(filter, update, options, callback){Promise.<Collection~updateWriteOpResultObject>}
-
Update multiple documents in a collection
Name Type Description filter
object The Filter used to select the documents to update
update
object The update operations to be applied to the documents
options
object optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
arrayFilters
Array optional optional list of array filters referenced in filtered positional operators
session
ClientSession optional optional session to use for this operation
callback
Collection~updateWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
updateOne(filter, update, options, callback){Promise}
-
Update a single document in a collection
Name Type 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 optional Optional settings.
Name Type Default Description upsert
boolean false optional Update operation is an upsert.
w
number | string optional The write concern.
wtimeout
number optional The write concern timeout.
j
boolean false optional Specify a journal write concern.
bypassDocumentValidation
boolean false optional Allow driver to bypass schema validation in MongoDB 3.2 or higher.
arrayFilters
Array optional optional list of array filters referenced in filtered positional operators
session
ClientSession optional optional session to use for this operation
callback
Collection~updateWriteOpCallback optional The command result callback
Returns:
Promise if no callback passed
-
watch(pipeline, options){ChangeStream}
-
Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
Name Type Description pipeline
Array optional An array of aggregation pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
options
object optional Optional settings
Name Type Default Description fullDocument
string 'default' optional Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
resumeAfter
object optional Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
maxAwaitTimeMS
number optional The maximum amount of time for the server to wait on new documents to satisfy a change stream query
batchSize
number optional The number of documents to return per batch. See aggregation documentation.
collation
object optional Specify collation settings for operation. See aggregation documentation.
readPreference
ReadPreference optional The read preference. Defaults to the read preference of the database or collection. See read preference documentation.
startAtClusterTime
Timestamp optional receive change events that occur after the specified timestamp
session
ClientSession optional optional session to use for this operation
- Since:
- 3.0.0
Returns:
ChangeStream instance.
Type Definitions
-
aggregationCallback(error, cursor)
-
The callback format for an aggregation call
Name Type Description error
MongoError An error instance representing the error during the execution.
cursor
AggregationCursor The cursor if the aggregation command was executed successfully.
-
bulkWriteOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
BulkWriteError An error instance representing the error during the execution.
result
Collection~BulkWriteOpResult The result object if the command was executed successfully.
-
BulkWriteOpResultObject
-
Properties:
Name Type Description insertedCount
number Number of documents inserted.
matchedCount
number Number of documents matched for update.
modifiedCount
number Number of documents modified.
deletedCount
number Number of documents deleted.
upsertedCount
number Number of documents upserted.
insertedIds
object Inserted document generated Id's, hash key is the index of the originating operation
upsertedIds
object Upserted document generated Id's, hash key is the index of the originating operation
result
object The command result object.
-
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.
-
deleteWriteOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~deleteWriteOpResult The result object if the command was executed successfully.
-
deleteWriteOpResultObject
-
Properties:
Name Type Description result
Object The raw result returned from MongoDB. Will vary depending on server version.
Properties
Name Type Description ok
Number Is 1 if the command executed correctly.
n
Number The total count of documents deleted.
connection
Object The connection object used for the operation.
deletedCount
Number The number of documents deleted.
-
findAndModifyCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~findAndModifyWriteOpResult The result object if the command was executed successfully.
-
findAndModifyWriteOpResultObject
-
Properties:
Name Type Description value
object Document returned from findAndModify command.
lastErrorObject
object The raw lastErrorObject returned from the command.
ok
Number Is 1 if the command executed correctly.
-
insertOneWriteOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~insertOneWriteOpResult The result object if the command was executed successfully.
-
insertOneWriteOpResultObject
-
Properties:
Name Type Description insertedCount
Number The total amount of documents inserted.
ops
Array.<object> All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
insertedId
ObjectId The driver generated ObjectId for the insert operation.
connection
object The connection object used for the operation.
result
object The raw command result object returned from MongoDB (content might vary by server version).
Properties
Name Type Description ok
Number Is 1 if the command executed correctly.
n
Number The total count of documents inserted.
-
insertWriteOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~insertWriteOpResult The result object if the command was executed successfully.
-
insertWriteOpResultObject
-
Properties:
Name Type Description insertedCount
Number The total amount of documents inserted.
ops
Array.<object> All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
insertedIds
Object.<Number, ObjectId> Map of the index of the inserted document to the id of the inserted document.
connection
object The connection object used for the operation.
result
object The raw command result object returned from MongoDB (content might vary by server version).
Properties
Name Type Description ok
Number Is 1 if the command executed correctly.
n
Number The total count of documents inserted.
-
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.
-
updateWriteOpCallback(error, result)
-
The callback format for inserts
Name Type Description error
MongoError An error instance representing the error during the execution.
result
Collection~updateWriteOpResult The result object if the command was executed successfully.
-
updateWriteOpResultObject
-
Properties:
Name Type Description result
Object The raw result returned from MongoDB. Will vary depending on server version.
Properties
Name Type Description ok
Number Is 1 if the command executed correctly.
n
Number The total count of documents scanned.
nModified
Number The total count of documents modified.
connection
Object The connection object used for the operation.
matchedCount
Number The number of documents that matched the filter.
modifiedCount
Number The number of documents that were modified.
upsertedCount
Number The number of documents upserted.
upsertedId
Object The upserted id.
Properties
Name Type Description _id
ObjectId The upserted _id returned from the server.
message
Object ops
Array -
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 using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
connection
object The connection object used for the operation.
result
object The command result object.