Docs 菜单
Docs 主页
/ / /
C++ 驱动程序
/

Delete Documents

在此页面上

  • Overview
  • 样本数据
  • 删除操作
  • 删除一个文档
  • 删除多个文档
  • 自定义删除操作
  • 返回值
  • API 文档

在本指南中,您可以学习;了解如何使用C++驾驶员通过执行删除操作从MongoDB集合中删除文档。

删除操作可从 MongoDB 集合中删除一个或多个文档。 您可以使用 delete_one()delete_many()方法执行删除操作。

本指南中的示例使用 Atlas示例数据集sample_restaurants数据库中的restaurants集合。 要从C++应用程序访问权限此集合,请实例化一个连接到Atlas 集群的mongocxx::client ,并将以下值分配给dbcollection变量:

auto db = client["sample_restaurants"];
auto collection = db["restaurants"];

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

您可以通过以下方法执行删除操作:

  • delete_one(),这会删除与 Atlas Search条件匹配的 第一个文档

  • delete_many(),这会删除与 Atlas Search条件匹配的 所有文档

每个删除方法都需要一个查询过滤文档,它指定搜索条件以确定选择要删除的文档。 有关查询筛选器的更多信息,请参阅MongoDB Server手册中的查询筛选器文档部分

以下示例使用delete_one()方法删除restaurants集合中name值为"Ready Penny Inn"的文档:

auto result = collection.delete_one(make_document(kvp("name", "Ready Penny Inn")));

以下示例使用delete_many()方法删除restaurants集合中borough值为"Brooklyn"的所有文档:

auto result = collection.delete_many(make_document(kvp("borough", "Brooklyn")));

您可以通过将mongocxx::options::delete_options类的实例作为可选参数传递来修改delete_one()delete_many()方法的行为。 下表描述了您可以在mongocxx::options::delete_options实例中设立的字段:

字段
说明
collation
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
write_concern
Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual.
hint
Gets or sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.
let
Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.
comment
Attaches a comment to the operation. For more information, see the delete command fields guide in the MongoDB Server manual.

以下示例调用 delete_many() 方法删除restaurants集合中 name 值包含string "Mongo" 的所有文档。 它还会设置mongocxx::options::delete_options实例的comment字段,以便为操作添加注释:

mongocxx::options::delete_options opts{};
opts.comment(bsoncxx::types::bson_value::view_or_value{"Deleting Mongo restaurants"});
auto query_filter = make_document(kvp("name", make_document(kvp("$regex", "Mongo"))));
auto result = collection.delete_many(query_filter.view(), opts);

提示

如果前面的示例使用delete_one()方法而不是delete_many() ,则驾驶员将仅删除name值包含"Mongo"的第一个文档。

delete_one()delete_many()方法返回mongocxx::result::delete_result类的实例。 该类包含以下成员函数:

  • result(),返回原始批量写入结果

  • deleted_count(),返回已删除的文档数

如果查询筛选器与任何文档都不匹配,则驱动程序不会删除任何文档,并且deleted_count为0 。

以下示例调用delete_many()方法来删除除cuisine值为"Greek"的文档。 然后,它调用deleted_count()成员函数来打印已删除文档的数量:

auto result = collection.delete_many(make_document(kvp("cuisine", "Greek")));
std::cout << result->deleted_count() << std::endl;
Deleted documents: 111

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

Update Documents