文档菜单
文档首页
/ / /
C++ 驱动
/

检索不同字段的值

在本页

  • 概述
  • 示例数据
  • distinct() 方法
  • 跨集合检索不同值
  • 跨指定文档检索不同值
  • 修改不同行为
  • API 文档

在本指南中,您可以学习如何使用 C++ 驱动程序跨集合检索指定字段的唯一值。

在一个集合中,不同的文档可能包含单个字段的不同的值。例如,一个restaurants 集合的 borough 值为 "Manhattan",另一个的 borough 值为 "Queens"。通过使用 C++ 驱动程序,您可以检索集合中多个文档中字段的全部唯一值。

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

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

有关如何创建免费的 MongoDB Atlas 集群并加载示例数据集的说明,请参阅 Atlas 入门 指南。

要获取指定字段的唯一值,请调用 distinct() 方法,并传入您想要获取唯一值的字段名称。

以下示例检索了 restaurants 集合中 borough 字段的唯一值。

auto cursor = collection.distinct("borough", {});
for(auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
{ "values" : [ "Bronx", "Brooklyn", "Manhattan", "Missing", "Queens", "Staten Island" ],
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { "$timestamp" : { ... } },
"signature" : { "hash" : { ... }, "keyId" : ... } }, "operationTime" : { "$timestamp" : { ... } }

此操作返回一个包含单个文档的游标。该文档包含 borough 字段的唯一值列表以及有关操作元数据。尽管有多个文档在 borough 字段中具有相同的值,但每个值在结果中只出现一次。

您可以为 distinct() 方法提供一个 查询过滤器,以在集合的子集文档中查找唯一字段值。查询过滤器是一个表达式,用于指定用于匹配操作中文档的搜索条件。有关创建查询过滤器的更多信息,请参阅指定查询指南。

以下示例检索了所有具有 cuisine 字段值为 "Italian" 的文档中 borough 字段的唯一值。

auto cursor = collection.distinct("borough", make_document(kvp("cuisine", "Italian")));
for(auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
{ "values" : [ "Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island" ],
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { "$timestamp" : { ... },
"signature" : { "hash" : { ... }, "keyId" : ... } }, "operationTime" : { "$timestamp" : { ... } }

您可以通过传递一个 mongocxx::options::distinct 类的实例作为参数来修改 distinct() 方法的行为。下表描述了您可以在一个 mongocxx::options::distinct 实例中设置的字段

字段
描述

collation

用于操作的排序规则。
类型: bsoncxx::document::view_or_value

max_time

操作可以运行的最大时间(以毫秒为单位)。
类型: std::chrono::milliseconds

comment

附加到操作的注释。
类型: bsoncxx::types::bson_value::view_or_value

read_preference

用于操作的读取偏好。
类型: mongocxx::read_preference

以下示例检索所有具有 borough 字段值为 "Bronx"cuisine 字段值为 "Pizza" 的文档的 name 字段的唯一值。它还指定了一个选项实例的 comment 字段以添加注释到操作

mongocxx::options::distinct opts{};
opts.comment(bsoncxx::types::bson_value::view_or_value{"Bronx pizza restaurants"});
auto cursor = collection.distinct("name",
make_document(kvp("$and",
make_array(make_document(kvp("borough", "Bronx")),
make_document(kvp("cuisine", "Pizza"))))),
opts
);
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
{ "values" : [ "$1.25 Pizza", "18 East Gunhill Pizza", "2 Bros", "Aenos Pizza", "Alitalia Pizza Restaurant", … ],
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { … }, "signature" : { … }, "keyId" : … } }, "operationTime" : { … } }

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

返回

指定要返回的字段