Overview
在此页面上,您可以查看可复制的代码示例,这些示例展示了可用于从MongoDB读取数据的常见Ruby驱动程序方法。
提示
要了解有关此页面上显示的任何方法的更多信息,请参阅每个部分中提供的链接。
To use an example from this page, copy the code example into the Sample Application below or your own application. Be sure to replace all placeholders in the code examples, such as <connection string URI>, with the relevant values for your MongoDB deployment.
示例应用程序
您可以使用以下示例应用程序来测试本页上的代码示例。 要使用示例应用程序,请执行以下步骤:
确保您已在Ruby项目中安装Ruby驱动程序。
复制以下代码并将其粘贴到新的
.rb文件中。从此页面复制代码示例,并将其粘贴到文件中的指定行。
1 require 'bundler/inline' 2 3 gemfile do 4 source 'https://rubygems.org' 5 gem 'mongo' 6 end 7 8 uri = '<connection string>' 9 10 Mongo::Client.new(uri) do |client| 11 database = client.use('<database name>') 12 collection = database['<collection name>'] 13 14 # Start example code here 15 16 # End example code here 17 end
查找一个
以下示例检索与给定过滤指定的条件相匹配的文档:
document = collection.find(name: '<value>').first puts document
要了解有关first方法的更多信息,请参阅检索数据指南。
查找多个
以下示例检索与给定过滤指定的条件匹配的所有文档:
results = collection.find(founded_year: '<value>')
要了解有关find方法的更多信息,请参阅检索数据指南。
对集合中的文档进行计数
以下示例返回指定集合中的文档数:
result = collection.count_documents puts "Number of documents: #{result}"
要学习;了解有关count_documents方法的更多信息,请参阅文档计数指南。
对查询返回的文档进行计数
以下示例返回指定集合中符合查询条件的文档数:
result = collection.count_documents('key': '<value>') puts "value: #{result}"
要学习;了解有关countDocuments()方法的更多信息,请参阅文档计数指南。
估计文档计数
以下示例根据集合元数据返回指定集合中文档的大致数量:
result = collection.estimated_document_count puts "Estimated number of documents: #{result}"
要学习;了解有关estimated_document_count()方法的更多信息,请参阅文档计数指南。
Retrieve Distinct Values
以下示例返回给定集合中指定字段名称的所有非重复值:
results = collection.distinct('field')
要了解有关distinct方法的更多信息,请参阅“检索不同字段值”指南。
监控数据变化
以下示例为给定集合创建变更流,并打印该集合中的后续变更事件:
stream = collection.watch collection.insert_one(a: 1) doc = stream.first process(doc)
要学习;了解有关watch()方法的更多信息,请参阅《监控数据更改》指南。