数据库和集合
MongoDB以层次结构组织数据。MongoDB部署包含一个或多个数据库,每个数据库包含一个或多个集合。在每个集合中,MongoDB将数据存储为包含字段-值对的文档。
先决条件
您必须在程序中包含以下导入语句,以运行本指南中的代码示例
import org.mongodb.scala._ import org.mongodb.scala.model.Filters._
注意
本指南使用Observable隐式,如《快速入门指南》中所述快速入门指南.
连接到MongoDB部署
首先,连接到一个正在运行的MongoDB部署。
以下代码连接到在本地主机(localhost)的端口(27017)上运行的独立MongoDB部署
val mongoClient = MongoClient()
有关连接到MongoDB部署的更多信息,请参阅连接到MongoDB教程。
访问数据库
一旦您已经有一个连接到 MongoDB 部署的 MongoClient 实例,使用 `getDatabase()` 方法来访问数据库。
将数据库名称作为参数传递给 getDatabase() 方法。如果数据库不存在,MongoDB 会在您向数据库插入任何数据时创建它。
以下示例访问了 test 数据库
val database: MongoDatabase = mongoClient.getDatabase("test")
访问集合
创建 MongoDatabase 实例后,使用 getCollection() 方法从该数据库访问集合。
将集合名称作为参数传递给 getCollection() 方法。
使用上一节中创建的 database 实例,以下代码访问了名为 myTestCollection 的集合
val coll: MongoCollection[Document] = database.getCollection("myTestCollection")
注意
MongoCollection 实例是不可变的。有关更多信息,请参阅本指南的 不可变性 部分。
如果不存在具有该名称的集合,MongoDB 会在您首次向该集合插入数据时创建它。
您还可以直接使用各种选项直接创建集合,例如设置最大大小或创建文档验证规则。
创建集合
驱动程序提供了createCollection()方法来直接创建集合。创建集合时,您可以使用CreateCollectionOptions类指定各种集合选项,例如最大大小或文档验证规则。
如果您没有指定任何选项,则不需要直接创建集合,因为MongoDB在您首次插入数据时会自动创建新集合。
固定集合
以下操作创建了一个限制为1兆字节的固定集合
database.createCollection("cappedCollection", CreateCollectionOptions().capped(true).sizeInBytes(0x100000)) .printResults()
有关固定集合的更多信息,请参阅服务器手册中的固定集合。
文档验证
MongoDB 允许您在更新和插入时验证文档。验证规则通过使用指定验证规则或表达式的过滤文档的ValidationOptions类在集合级别指定。
以下示例创建了一个具有模式验证的集合
ValidationOptions collOptions = ValidationOptions().validator( Filters.or(Filters.exists("email"), Filters.exists("phone"))) database.createCollection("contacts", CreateCollectionOptions().validationOptions(collOptions)) .printResults()
有关文档验证的更多信息,请参阅服务器手册中的模式验证。
获取集合列表
您可以通过使用 MongoDatabase.listCollectionNames() 方法获取数据库中集合的列表
database.listCollectionNames().printResults()
删除集合
您可以使用 MongoCollection.drop() 方法删除集合并删除集合中的所有数据
val collection: MongoCollection[Document] = database.getCollection("contacts") collection.drop().printResults()
不可变性
MongoDatabase 和 MongoCollection 实例是不可变的。要从具有不同属性(如不同的 读取关注点、读取偏好 和 写入关注点)的现有实例创建新实例,MongoDatabase 和 MongoCollection 类提供了以下方法
MongoDatabase.withReadConcern()MongoDatabase.withReadPreference()MongoDatabase.withWriteConcern()MongoCollection.withReadConcern()MongoCollection.withReadPreference()MongoCollection.withWriteConcern()
编解码器注册表
对 getCollection() 方法的重载允许您指定用于表示 BSON 文档的不同类。例如,您可能想使用严格且类型安全的 BsonDocument 类来模拟您的文档,在执行 CRUD 操作时
import org.mongodb.scala.bson._ val collection: MongoCollection[BsonDocument] = database.getCollection[BsonDocument]("mycoll") // insert a document val document = BsonDocument("{x: 1}") collection.insertOne(document).printResults() document.append("x", BsonInt32(2)).append("y", BsonInt32(3)) // replace a document collection.replaceOne(Filters.equal("_id", document.get("_id")), document) .printResults() // find documents collection.find().printResults()
任何以这种方式使用的类都必须满足以下两个要求
该类的
Codec实例必须注册在CodecRegistry中的MongoCollection。Codec实例必须能够编码和解码完整的 BSON 文档,而不仅仅是例如单个 BSON 值如Int32。
默认情况下,MongoCollection 配置了四个类的 Codec 实例
Document(Scala 的BsonDocument包装器)BsonDocumentDocument(Java 驱动的松散类型Document类)BasicDBObject
应用程序可以通过自定义 CodecRegistry 来注册其他类的 Codec 实现。新的 CodecRegistry 实例可以在以下级别进行配置
在
MongoClient中的MongoClientSettings在其
withCodecRegistry方法中的MongoDatabase在其
withCodecRegistry方法中的MongoCollection
考虑编码和解码 UUID 类实例的情况。默认情况下,驱动程序使用与其他 MongoDB 驱动程序不兼容的字节序来编码 UUID 实例,更改默认设置会非常危险。
对于需要跨多个驱动程序互操作的新应用程序,可以更改该默认设置,他们可以通过指定一个 CodecRegistry 来实现
// replaces the default UuidCodec with one that uses the new standard UUID representation import org.bson.UuidRepresentation import org.bson.codecs.UuidCodec import org.bson.codecs.configuration.CodecRegistries val codecRegistry = CodecRegistries.fromRegistries( CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClient.DEFAULT_CODEC_REGISTRY) // globally val settings = MongoClientSettings.builder() .codecRegistry(codecRegistry).build() val client = MongoClient(settings) // or at the database level val database = client.getDatabase("mydb") .withCodecRegistry(codecRegistry) // or at the collection level val collection = database.getCollection("mycoll") .withCodecRegistry(codecRegistry)