从 MongoDB 读取数据
概述
在本页,您可以查看可复制代码示例,展示了检索文档的常见C++驱动程序方法。
提示
要了解更多关于本页展示的任何方法,请参阅每个部分提供的链接。
要使用本页的示例,将代码示例复制到示例应用程序或您自己的应用程序中。确保用您MongoDB部署的相关值替换所有占位符,例如<连接字符串>
。
示例应用程序
您可以使用以下示例应用程序测试本页的代码示例。要使用示例应用程序,请执行以下步骤
确保您已将C++驱动程序安装到您的项目可以导入的位置。
复制以下代码,并将其粘贴到您的项目中的一个新
.cpp
文件中。从本页复制一个代码示例,并将其粘贴到文件的高亮部分。
1 2 3 4 5 6 7 8 9 10 using bsoncxx::builder::basic::kvp; 11 using bsoncxx::builder::basic::make_document; 12 13 int main() { 14 try { 15 mongocxx::instance instance; 16 17 mongocxx::uri uri("<connection string>"); 18 mongocxx::client client(uri); 19 20 auto database = client["<database name>"]; 21 auto collection = database["<collection name>"]; 22 23 // Start example code here 24 25 // End example code here 26 27 } catch (const mongocxx::exception& e) { 28 std::cout << "An exception occurred: " << e.what() << "\n"; 29 return EXIT_FAILURE; 30 } 31 32 return EXIT_SUCCESS; 33 }
查找单个
以下代码演示了如何从满足指定条件的集合中检索单个文档
auto result = collection.find_one(make_document(kvp("<field name>", "<value>"))); std::cout << bsoncxx::to_json(*result) << std::endl;
要了解有关 find_one()
方法的更多信息,请参阅查找单个文档 部分的数据检索指南。
查找多个
以下代码演示了如何从满足指定条件的集合中检索所有文档
auto results = collection.find(make_document(kvp("<field name>", "<value>"))); for(auto&& doc : results) { std::cout << bsoncxx::to_json(doc) << std::endl; }
要了解有关 find()
方法的更多信息,请参阅查找多个文档 部分的数据检索指南。
统计集合中的文档数量
以下代码演示了如何统计集合中文档的数量
auto result = collection.count_documents({}); std::cout << result << std::endl;
要了解有关 count_documents()
方法的更多信息,请参阅获取精确计数 部分的文档计数指南。
查询返回的文档计数
以下代码展示了如何计算符合特定条件的集合中的文档数量
auto result = collection.count_documents(make_document(kvp("<field name>", "<value>"))); std::cout << result << std::endl;
要了解有关 count_documents()
方法的更多信息,请参阅获取精确计数 部分的文档计数指南。
估计文档计数
以下代码展示了如何检索集合中文档数量的估计值
auto result = collection.estimated_document_count(); std::cout << result << std::endl;
要了解更多关于 estimated_document_count()
方法的信息,请参阅 Count Documents 指南中的 检索估计计数 部分。
检索唯一值
以下代码展示了如何检索符合特定条件的文档字段的唯一值
auto results = collection.distinct("<field name>", "<filter>"); for(auto&& doc : results) { std::cout << bsoncxx::to_json(doc) << std::endl; }
要了解更多关于 distinct()
方法的知识,请参阅 检索唯一字段值 指南。
监控数据变化
以下代码展示了如何监控和打印集合的变化
auto stream = collection.watch(); while (true) { for (const auto& event : stream) { std::cout << bsoncxx::to_json(event) << std::endl; } }
要了解更多关于 watch()
方法的知识,请参阅监控数据变化指南。