Docs 菜单
Docs 主页
/ / /
Scala
/

快速入门(案例类示例)

在此页面上

  • Overview
  • 配置案例类
  • 插入人员
  • 插入多个 Person 实例
  • 查询集合
  • 查找第一个匹配的人员
  • 返回所有文档
  • 使用查询筛选器检索人员
  • 查找匹配的 Person 实例
  • Update Documents
  • Delete Documents

本指南与快速入门指南类似,但使用案例类对文档进行建模,而不是使用通用的 Document类。

本指南中的代码示例来自 QuickTourCaseClass.scala 驱动程序源代码Github 存储库中的文件。

重要

有关使用宏为MongoCollection实例配置案例类支持的信息,请参阅BSON 宏文档。

首先,创建要用于表示集合中文档的案例类。以下代码创建一个Person案例类和伴生对象:

import org.mongodb.scala.bson.ObjectId
object Person {
def apply(firstName: String, lastName: String): Person =
Person(new ObjectId(), firstName, lastName)
}
case class Person(_id: ObjectId, firstName: String, lastName: String)

注意

在伴随对象中, apply()方法可以在创建不含 _id 的新实例时自动分配值。在 MongoDB 中, _id字段表示文档的主键,因此通过在案例类中包含_id字段,您可以允许访问主键。

Person与集合一起使用时,必须有一个可以将其与 BSON 相互转换的Codecorg.mongodb.scala.bson.codecs.Macros伴生对象提供的宏可以在编译时自动为案例类生成编解码器。以下示例创建了一个新的CodecRegistry ,其中包括Person案例类的编解码器:

import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.MongoClient.DEFAULT_CODEC_REGISTRY
import org.bson.codecs.configuration.CodecRegistries.{fromRegistries, fromProviders}
val codecRegistry = fromRegistries(fromProviders(classOf[Person]), DEFAULT_CODEC_REGISTRY )

配置CodecRegistry后,下一步是创建MongoCollection[Person] 。以下示例使用mydb数据库中的test集合:

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry)
val collection: MongoCollection[Person] = database.getCollection("test")

注意

可以在创建MongoClient时、数据库级别或集合级别设置CodecRegistry 。 该 API 非常灵活,可根据需要使用不同的CodecRegistry实例。

使用正确配置的MongoCollection后,将Person实例插入集合就很简单:

val person: Person = Person("Ada", "Lovelace")
collection.insertOne(person).results()

要插入多个Person实例,请使用insertMany()方法。 以下示例使用printResults()隐式并阻塞,直到观察器完成,然后打印每个结果:

val people: Seq[Person] = Seq(
Person("Charles", "Babbage"),
Person("George", "Boole"),
Person("Gertrude", "Blanch"),
Person("Grace", "Hopper"),
Person("Ida", "Rhodes"),
Person("Jean", "Bartik"),
Person("John", "Backus"),
Person("Lucy", "Sanders"),
Person("Tim", "Berners Lee"),
Person("Zaphod", "Beeblebrox")
)
collection.insertMany(people).printResults()

此代码输出以下消息:

The operation completed successfully

使用find()方法查询集合。

查询集合使用的 API 与快速入门中使用的 API 相同:

collection.find().first().printHeadResult()

该示例打印集合中的第一个Person

Person(58dd0a68218de22333435fa4, Ada, Lovelace)

要检索集合中的所有文档,请使用find()方法。 find()方法返回一个FindObservable实例,该实例为链接或控制查找操作提供流畅的接口。 以下示例会将集合中的所有文档打印为Person实例:

collection.find().printResults()

要返回集合中文档的子集,请将筛选器传递给find()方法。 例如,以下示例返回名字为Person 的第一个"Ida"

import org.mongodb.scala.model.Filters._
collection.find(equal("firstName", "Ida")).first().printHeadResult()

此示例输出以下结果:

Person(58dd0a68218de22333435fa4, Ida, Rhodes)

提示

您可以使用FiltersSortsProjectionsUpdates辅助方法以简单明了的方式构建查询。

以下筛选器查找 以 开头的所有Person firstName"G"实例,并按lastName 排序:

collection.find(regex("firstName", "^G")).sort(ascending("lastName")).printResults()

此示例打印输出"Gertrude""George""Grace"Person实例。

MongoDB 支持许多更新操作符。 使用Updates助手帮助更新集合中的文档。

以下更新更正了"Tim Berners-Lee"的连字符:

collection.updateOne(equal("lastName", "Berners Lee"), set("lastName", "Berners-Lee"))
.printHeadResult("Update Result: ")

更新方法返回UpdateResult ,其中提供有关操作的信息,包括更新修改的文档数。

要最多删除一个文档,或者在没有文档与过滤器匹配的情况下不删除文档,请使用deleteOne()方法:

collection.deleteOne(equal("firstName", "Zaphod")).printHeadResult("Delete Result: ")

后退

快速入门