Overview
在本指南中,您可以学习;了解如何使用C++驾驶员检索集合中指定字段的不同值。
在集合中,不同文档的单个字段可能包含不同值。 示例, restaurants集合中的一个文档的borough值为"Manhattan" ,而另一文档的borough值为"Queens" 。 通过使用C++驾驶员,您可以检索集合中多个文档中某个字段包含的所有唯一值。
样本数据
本指南中的示例使用 Atlas示例数据集的sample_restaurants数据库中的restaurants集合。 要从C++应用程序访问权限此集合,请实例化一个连接到Atlas 集群的mongocxx::client ,并将以下值分配给db和collection变量:
auto db = client["sample_restaurants"]; auto collection = db["restaurants"];
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
distinct() 方法
要检索指定字段的非重复值,请调用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实例中设立的字段:
字段 | 说明 |
|---|---|
| The collation to use for the operation. Type: bsoncxx::document::view_or_value |
| The maximum amount of time in milliseconds that the operation can run. Type: std::chrono::milliseconds |
| The comment to attach to the operation. Type: bsoncxx::types::bson_value::view_or_value |
| The read preference to use for the operation. Type: 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 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: