文档菜单
文档首页
/ / /
Java反应式流驱动程序

数据库和集合

本页内容

  • 先决条件
  • 连接到 MongoDB 部署
  • 访问数据库
  • 访问集合
  • 创建集合
  • 获取集合列表
  • 删除集合
  • 不可变性
  • CodecRegistry

MongoDB 以分层结构组织数据。一个 MongoDB 部署包含一个或多个数据库,每个数据库包含一个或多个集合。在每个集合中,MongoDB 以包含字段和值对的文档形式存储数据。

您必须将以下导入语句包含在程序中,才能运行本指南中的代码示例

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import static com.mongodb.client.model.Filters.*;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.ValidationOptions;

重要

本指南使用自定义Subscriber 实现,这些实现已在示例自定义订阅者实现 指南中描述。

首先,连接到一个运行的 MongoDB 部署。

以下代码连接到在本地主机 localhost 的端口 27017 上运行的独立 MongoDB 部署

MongoClient mongoClient = MongoClients.create();

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

一旦你有一个连接到MongoDB部署的MongoClient实例,请使用`getDatabase()`方法来访问数据库。

将数据库名称作为参数传递给getDatabase()方法。如果数据库不存在,当你向数据库插入数据时,MongoDB会创建它。

以下示例访问了test数据库

MongoDatabase database = mongoClient.getDatabase("test");

注意

MongoDatabase实例是不可变的。有关更多信息,请参阅本指南的不可变性部分。不可变性

创建一个MongoDatabase实例后,请使用getCollection()方法从该数据库中访问集合。

将集合名称作为参数传递给getCollection()方法。

使用上一节中创建的database实例,以下代码访问了名为myTestCollection的集合

MongoCollection<Document> coll = database.getCollection("myTestCollection");

注意

MongoCollection实例是不可变的。有关更多信息,请参阅本指南的不可变性部分。

如果不存在具有该名称的集合,当你首次向该集合插入数据时,MongoDB会创建它。

您还可以直接使用各种选项创建集合,例如设置最大大小或创建文档验证规则。

驱动程序提供了createCollection()方法来直接创建集合。当创建集合时,您可以使用CreateCollectionOptions类指定各种集合选项,例如最大大小或文档验证规则。

如果您没有指定任何选项,则不需要直接创建集合,因为MongoDB在首次插入数据时会自动创建新集合。

以下操作创建了一个限制为1兆字节的固定集合

database.createCollection(
"cappedCollection",
new CreateCollectionOptions().capped(true).sizeInBytes(0x100000)
).subscribe(new OperationSubscriber<Void>());

有关固定集合的更多信息,请参阅服务器手册中的固定集合

MongoDB允许您在更新和插入文档时进行文档验证。验证规则通过使用指定验证规则或表达式的过滤器文档的ValidationOptions类在集合级别进行指定。

以下示例创建了一个具有模式验证的集合

ValidationOptions collOptions = new ValidationOptions().validator(
Filters.or(Filters.exists("email"), Filters.exists("phone")));
database.createCollection(
"contacts",
new CreateCollectionOptions().validationOptions(collOptions)
).subscribe(new OperationSubscriber<Void>());

有关文档验证的更多信息,请参阅服务器手册中的模式验证

您可以通过使用 MongoDatabase.listCollectionNames() 方法获取数据库中集合的列表

database.listCollectionNames().subscribe(new PrintToStringSubscriber<String>());

您可以通过使用 MongoCollection.drop() 方法删除集合并删除集合中的所有数据

MongoCollection<Document> collection = database.getCollection("contacts");
collection.drop().subscribe(new OperationSubscriber<Void>());

MongoDatabaseMongoCollection 实例是不可变的。要从具有不同属性(如不同的读取关注点读取偏好写入关注点)的现有实例创建新实例,MongoDatabaseMongoCollection 类提供了以下方法

  • MongoDatabase.withReadConcern()

  • MongoDatabase.withReadPreference()

  • MongoDatabase.withWriteConcern()

  • MongoCollection.withReadConcern()

  • MongoCollection.withReadPreference()

  • MongoCollection.withWriteConcern()

有关更多信息,请参阅从 MongoDB 读取数据向 MongoDB 写入数据教程。

getCollection() 方法的重载允许您指定用于表示 BSON 文档的不同类。例如,您可能希望在使用 CRUD 操作时使用严格且类型安全的 BsonDocument 类来建模您的文档。

// pass BsonDocument.class as the second argument
MongoCollection<BsonDocument> collection = database
.getCollection("mycoll", BsonDocument.class);
// insert a document
BsonDocument document = BsonDocument.parse("{x: 1}");
collection.insertOne(document).subscribe(new OperationSubscriber<Void>());
document.append("x", new BsonInt32(2)).append("y", new BsonInt32(3));
// replace a document
collection.replaceOne(Filters.eq("_id", document.get("_id")), document)
.subscribe(new PrintSubscriber<UpdateResult>("Update Result: %s"));
// find documents
collection.find().subscribe(new PrintDocumentSubscriber());

任何类要以此种方式使用,必须满足以下两个要求

  • 该类的 Codec 实例必须注册在 MongoCollectionCodecRegistry 中。

  • Codec 实例必须是可以编码和解码整个 BSON 文档的实例,而不仅仅是例如 Int32 这样的单个 BSON 值。

默认情况下,MongoCollection 配置了三个类的 Codec 实例

  • 文档

  • BsonDocument

  • BasicDBObject

应用程序可以自定义 CodecRegistry 以注册其他类的 Codec 实现。新的 CodecRegistry 实例可以在以下级别进行配置

  • MongoClient 中的 MongoClientSettings

  • 在其 withCodecRegistry 方法中的 MongoDatabase

  • 在其 withCodecRegistry 方法中的 MongoCollection

考虑对 UUID 类的实例进行编码和解码的情况。默认情况下,驱动程序使用与其他 MongoDB 驱动程序不兼容的字节序来编码 UUID 的实例,更改默认值可能会很危险。

对于需要跨多个驱动程序互操作的新应用程序,可以更改该默认值,并且它们可以通过指定 CodecRegistry 来做到这一点。

// replaces the default UuidCodec to use the standard UUID representation
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)
), MongoClientSettings.getDefaultCodecRegistry());
// globally
MongoClientSettings settings = MongoClientSettings.builder()
.codecRegistry(codecRegistry).build();
MongoClient client = MongoClients.create(settings);
// or per database
MongoDatabase database = client.getDatabase("mydb")
.withCodecRegistry(codecRegistry);
// or per collection
MongoCollection<Document> collection = database.getCollection("mycoll")
.withCodecRegistry(codecRegistry);

返回

稳定 API