Collection
6 methodsCollection-level operations exposed by the driver and mongo shell.
collection.insertOne(document, options?) -> InsertOneResultInserts a single document into the collection.
Parameters
| Name | Type | Description |
|---|---|---|
| document | object | Document to insert; _id auto-generated if absent. |
| options | object | Optional writeConcern or session. |
Returns
InsertOneResult
Example
mongodb
db.users.insertOne({ name: 'Ada', age: 36 });collection.find(query, projection?) -> CursorReturns a cursor over documents matching the query, optionally projecting fields.
Parameters
| Name | Type | Description |
|---|---|---|
| query | object | Selector document; {} matches all. |
| projection | object | Field inclusion/exclusion map. |
Returns
Cursor
Example
mongodb
db.users.find({ active: true }, { name: 1, _id: 0 });collection.updateOne(filter, update, options?) -> UpdateResultUpdates the first document matching filter using update operators such as $set.
Parameters
| Name | Type | Description |
|---|---|---|
| filter | object | Query selecting the document to update. |
| update | object | Update operators document, e.g. { $set: {...} }. |
| options | object | Optional upsert, arrayFilters. |
Returns
UpdateResult
Example
mongodb
db.users.updateOne({ _id: 1 }, { $set: { age: 37 } });collection.deleteOne(filter, options?) -> DeleteResultDeletes the first document matching the filter.
Parameters
| Name | Type | Description |
|---|---|---|
| filter | object | Query selecting the document to delete. |
Returns
DeleteResult
Example
mongodb
db.users.deleteOne({ _id: 1 });collection.aggregate(pipeline, options?) -> CursorRuns an aggregation pipeline returning a cursor over the resulting documents.
Parameters
| Name | Type | Description |
|---|---|---|
| pipeline | object[] | Array of aggregation stages. |
Returns
Cursor
Example
mongodb
db.orders.aggregate([
{ $match: { status: 'shipped' } },
{ $group: { _id: '$custId', total: { $sum: '$amount' } } }
]);collection.countDocuments(filter, options?) -> numberReturns the number of documents matching the filter.
Parameters
| Name | Type | Description |
|---|---|---|
| filter | object | Query selector. |
Returns
number
Example
mongodb
db.users.countDocuments({ active: true });