Skip to content

MongoDB Collection API

MongoDB 查询和聚合操作符,用于过滤、转换和分组文档。

1 class · 6 methods

Operators

6 methods

常用查询和管道操作符。

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

过滤文档的聚合阶段,行为类似于集合 find 查询。

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

按 _id 表达式分组文档并对每个字段应用累加器的聚合阶段。

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

仅将指定字段(含可选计算值)传递到下游的聚合阶段。

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

对同一数据库中的另一个集合执行左外连接。

Parameters

NameTypeDescription
filterobjectQuery selecting the document to delete.

Returns

DeleteResult

Example

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

按给定字段排序文档的聚合阶段;1 升序,-1 降序。

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 });