Skip to content

MongoDB Collection API

MongoDB collection methods for inserting, querying, updating and aggregating documents.

1 class · 6 methods

Collection

6 methods

Collection-level operations exposed by the driver and mongo shell.

collection.insertOne(document, options?) -> InsertOneResult

Inserts a single document into the collection.

Parameters

NameTypeDescription
documentobjectDocument to insert; _id auto-generated if absent.
optionsobjectOptional writeConcern or session.

Returns

InsertOneResult

Example

mongodb
db.users.insertOne({ name: 'Ada', age: 36 });
collection.find(query, projection?) -> Cursor

Returns a cursor over documents matching the query, optionally projecting fields.

Parameters

NameTypeDescription
queryobjectSelector document; {} matches all.
projectionobjectField inclusion/exclusion map.

Returns

Cursor

Example

mongodb
db.users.find({ active: true }, { name: 1, _id: 0 });
collection.updateOne(filter, update, options?) -> UpdateResult

Updates the first document matching filter using update operators such as $set.

Parameters

NameTypeDescription
filterobjectQuery selecting the document to update.
updateobjectUpdate operators document, e.g. { $set: {...} }.
optionsobjectOptional upsert, arrayFilters.

Returns

UpdateResult

Example

mongodb
db.users.updateOne({ _id: 1 }, { $set: { age: 37 } });
collection.deleteOne(filter, options?) -> DeleteResult

Deletes the first document matching the filter.

Parameters

NameTypeDescription
filterobjectQuery selecting the document to delete.

Returns

DeleteResult

Example

mongodb
db.users.deleteOne({ _id: 1 });
collection.aggregate(pipeline, options?) -> Cursor

Runs an aggregation pipeline returning a cursor over the resulting documents.

Parameters

NameTypeDescription
pipelineobject[]Array of aggregation stages.

Returns

Cursor

Example

mongodb
db.orders.aggregate([
  { $match: { status: 'shipped' } },
  { $group: { _id: '$custId', total: { $sum: '$amount' } } }
]);
collection.countDocuments(filter, options?) -> number

Returns the number of documents matching the filter.

Parameters

NameTypeDescription
filterobjectQuery selector.

Returns

number

Example

mongodb
db.users.countDocuments({ active: true });