Docs 菜单
Docs 主页
/ /
Tutorials

读取操作

读取操作从集合中检索文档或文档信息。 您可以指定筛选器,仅检索符合筛选条件的文档。

您必须设置以下组件才能运行本指南中的代码示例:

  • 一个 test.restaurants集合,其中填充了来自文档资产Githubrestaurants.json文件的文档。

  • 以下 import 语句:

import org.mongodb.scala._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Projections._
import org.mongodb.scala.model.Sorts._

注意

本指南使用快速入门入门中所述的Observable隐式。

首先,连接到 MongoDB 部署,然后声明并定义MongoDatabaseMongoCollection实例。

以下代码连接到在端口27017上的localhost上运行的独立 MongoDB 部署。 然后,定义database变量以引用test数据库,并collection变量以引用restaurants集合:

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("test")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

要了解有关连接到 MongoDB 部署的更多信息,请参阅连接到 MongoDB教程。

要查询集合,可以使用集合的find()方法。

您可以不带任何参数调用该方法来查询集合中的所有文档:

collection.find().printResults()

或者,您可以传递筛选器来查询与筛选条件匹配的文档:

collection.find(equal("name", "456 Cookies Shop"))
.printResults()

要查询匹配特定条件的文档,请将筛选器文档传递给find()方法。

要指定空筛选器并匹配集合中的所有文档,请使用空Document对象:

collection.find(Document()).printResults()

提示

使用find()方法时,您还可以在不传递任何筛选器对象的情况下调用该方法来匹配集合中的所有文档。

collection.find().printResults()

为了便于创建过滤器文档,驱动程序提供了 Filters 类,该类提供过滤器条件辅助方法。要学习;了解这些方法,请参阅 筛选器生成器类指南。

此示例查找操作包含一个筛选器Document实例,该实例指定以下条件:

  • stars 字段值大于或等于2且小于5

  • categories 字段等于 "Bakery",或者如果 categories 是数组字段,则包含string "Bakery" 作为元素

collection.find(
Document("stars" -> Document("$gte" -> 2, "$lt"-> 5, "categories" -> "Bakery")))
.printResults()

以下示例使用Filters辅助方法指定相同的筛选条件:

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
.printResults()

要查看查询过滤操作符列表,请参阅服务器手册中的查询和投影操作符。要查看 Filters 助手列表,请参阅筛选器API文档。

find()方法返回FindObservable类的实例。 该类提供了各种方法,您可以链接到find()方法,以修改查询的输出或行为,例如sort()projection() ,以及通过subscribe()方法迭代结果。

默认情况下,MongoDB 中的查询返回匹配文档中的所有字段。 要指定要在匹配文档中返回的字段,可以指定投影文档。

此查找操作示例包含一个投影Document ,该投影指定匹配文档仅包含namestarscategories字段:

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
.projection(Document("name" -> 1, "stars" -> 1, "categories" -> 1, "_id" -> 0))
.printResults()

为了便于创建投影文档,驱动程序提供了 Projections 类辅助工具方法。要学习;了解有关这些方法的更多信息,请参阅 投影生成器类指南。

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
.projection(fields(include("name", "stars", "categories"), excludeId()))
.printResults()

在投影文档中,您还可以使用投影操作符指定投影表达式。

要查看使用 Projections.metaTextScore() 方法的示例,请参阅文本Atlas Search教程。

要对文档进行排序,请将排序规范文档传递给 FindObservable.sort() 方法。驱动程序提供了 Sorts 辅助工具方法来促进排序规范文档的创建。要学习如何使用构建者构建排序条件,请参阅排序构建器类指南。

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
.sort(ascending("name"))
.printResults()

FindObservable方法本身返回FindObservable对象,因此,您可以将多个FindObservable方法附加到find()方法:

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.explain()
.printResults()

要解释查找操作,请调用FindObservable.explain()方法:

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.explain()
.printResults()

对于副本集或分片集群上的读取操作,您可以在以下级别配置读取偏好:

  • MongoClient中通过以下方式:

    • 通过创建MongoClientSettings实例:

      val mongoClient = MongoClient(MongoClientSettings.builder()
      .applyConnectionString(ConnectionString("mongodb://host1,host2"))
      .readPreference(ReadPreference.secondary())
      .build())
    • 通过创建ConnectionString实例:

      val mongoClient = MongoClient("mongodb://host1:27017,host2:27017/?readPreference=secondary")
  • MongoDatabase中,使用withReadPreference()方法:

    val database = mongoClient.getDatabase("test")
    .withReadPreference(ReadPreference.secondary())
  • MongoCollection中,使用withReadPreference()方法:

    val collection = database.getCollection("restaurants")
    .withReadPreference(ReadPreference.secondary())

MongoDatabaseMongoCollection实例是不可变的。 在现有MongoDatabaseMongoCollection实例上调用withReadPreference()会返回一个新实例,并且不会影响调用该方法的实例。

在以下示例中, collectionWithReadPref实例的读取偏好为primaryPreferred ,而collection的读取偏好不受影响:

val collectionWithReadPref = collection.withReadPreference(ReadPreference.primaryPreferred())

对于副本集或分片集群上的读取操作,应用程序可以在以下级别配置读关注:

  • MongoClient中通过以下方式:

    • 通过创建MongoClientSettings实例:

      val mongoClient = MongoClient(MongoClientSettings.builder()
      .applyConnectionString(ConnectionString("mongodb://host1,host2"))
      .readConcern(ReadConcern.MAJORITY)
      .build())
    • 通过创建ConnectionString实例:

      val mongoClient = MongoClient("mongodb://host1:27017,host2:27017/?readConcernLevel=majority")
  • MongoDatabase中,使用withReadConcern()方法:

    val database = mongoClient.getDatabase("test")
    .withReadConcern(ReadConcern.MAJORITY)
  • MongoCollection中,使用withReadConcern()方法:

    val collection = database.getCollection("restaurants")
    .withReadConcern(ReadConcern.MAJORITY)

MongoDatabaseMongoCollection实例是不可变的。 在现有MongoDatabaseMongoCollection实例上调用withReadConcern()会返回一个新实例,并且不会影响调用该方法的实例。

在以下示例中, collWithReadConcern实例有一个AVAILABLE读关注,而collection的读关注不受影响:

val collWithReadConcern = collection.withReadConcern(ReadConcern.AVAILABLE)

您可以构建MongoClientSettingsMongoDatabaseMongoCollection实例以包含读关注、读取偏好和写关注的组合。

例如,以下代码在集合级别设置所有三个:

val collection = database.getCollection("restaurants")
.withReadPreference(ReadPreference.primary())
.withReadConcern(ReadConcern.MAJORITY)
.withWriteConcern(WriteConcern.MAJORITY)

后退

createIndexes

在此页面上