文档菜单
文档首页
/ / /
Scala
/

快速入门(案例类示例)

本页内容

  • 概述
  • 配置案例类
  • 插入一个人员
  • 插入多个人员实例
  • 查询集合
  • 找到第一个匹配的人员
  • 返回所有文档
  • 使用查询过滤器检索人员
  • 找到匹配的人员实例
  • 更新文档
  • 删除文档

本指南类似于快速入门指南,但使用案例类来模拟文档而不是使用通用Document 类。

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

重要

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

首先,创建一个用于表示集合中文档的case类。以下代码创建了一个Person case类及其伴生对象

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的新实例时自动分配一个_id值。在MongoDB中,_id字段表示文档的主键,因此,在case类中包含_id字段,您可以访问主键。

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

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

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

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

Person(58dd0a68218de22333435fa4, Ada, Lovelace)

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

collection.find().printResults()

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

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

此示例输出以下结果

Person(58dd0a68218de22333435fa4, Ida, Rhodes)

提示

您可以使用 过滤器排序投影更新 辅助器以实现简单简洁的查询构建方式。

以下过滤器查找所有以 "G" 开头的 Person 实例,并按 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: ")

返回

快速入门