文档菜单
文档首页
/ / /
Java 同步驱动程序
/ / /

插入操作

本页内容

  • 概述
  • 关于_id
  • 插入单个文档
  • 插入多个文档
  • 总结

在本指南中,您可以学习如何使用MongoDB Java驱动程序插入文档。

您可以使用MongoDB检索、更新和删除信息。要执行这些操作中的任何一项,例如用户资料和订单等信息需要存在于MongoDB中。为了使这些信息存在,首先执行插入操作。

插入操作使用insertOne()insertMany()bulkWrite()方法将单个或多个文档插入MongoDB。

以下部分重点介绍insertOne()insertMany()。有关如何使用bulkWrite()方法的更多信息,请参阅我们的批量操作指南.

在插入文档时,MongoDB默认对您的文档强制实施一个约束:每个文档必须包含一个唯一的_id字段。

有两种方法来管理此字段

  • 您可以自行管理此字段,确保您使用的每个值都是唯一的。

  • 您可以允许驱动程序自动生成唯一的ObjectId值。

除非您提供了强唯一性保证,否则我们建议您让驱动程序自动生成_id值。

注意

重复的_id值违反了唯一索引约束,导致出现WriteError

有关唯一索引的更多信息,请参阅手册条目唯一索引.

当您想插入单个文档时,请使用 insertOne() 方法。

成功插入后,该方法返回一个表示新文档 _idInsertOneResult 实例。

以下示例展示了如何使用 insertOne() 方法创建并插入一个文档

Document doc1 = new Document("color", "red").append("qty", 5);
InsertOneResult result = collection.insertOne(doc1);
System.out.println("Inserted a document with the following id: "
+ result.getInsertedId().asObjectId().getValue());

上述代码的输出类似于以下内容

Inserted a document with the following id: 60930c39a982931c20ef6cd6

有关本节中提到的方法和类的更多信息,请参阅以下资源

当您想插入多个文档时,请使用 insertMany() 方法。此方法按照指定的顺序插入文档,直到发生异常,如果有的话。

例如,假设您想插入以下文档

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }
{ "_id": 3, "color": "yellow", "qty": 3 }
{ "_id": 6, "color": "blue", "qty": 8 }

如果您尝试插入这些文档,第三个文档将发生 WriteError,错误之前的文档将插入到您的集合中。

提示

使用 try-catch 块在错误发生之前获取已成功处理的文档的确认

List<Integer> insertedIds = new ArrayList<>();
// Inserts sample documents and prints their "_id" values
try {
InsertManyResult result = collection.insertMany(documents);
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asInt32().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);
// Prints a message if any exceptions occur during the operation and the "_id" values of inserted documents
} catch(MongoBulkWriteException exception) {
exception.getWriteResult().getInserts()
.forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue()));
System.out.println("A MongoBulkWriteException occurred, but there are " +
"successfully processed documents with the following ids: " + insertedIds);
}

输出由 MongoDB 可以处理的文档组成,应类似于以下内容

A MongoBulkWriteException occurred, but there are successfully processed
documents with the following ids: [3, 4, 6]

如果您查看您的集合,您应该看到以下文档

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }

在成功插入后,该方法返回一个代表每个新文档的 _idInsertManyResult 实例。

以下示例创建并添加两个文档到一个列表,并使用insertMany()方法插入该列表

List<Document> documents = new ArrayList<>();
Document doc1 = new Document("color", "red").append("qty", 5);
Document doc2 = new Document("color", "purple").append("qty", 10);
documents.add(doc1);
documents.add(doc2);
InsertManyResult result = collection.insertMany(documents);
// Retrieves and prints the ID values of each inserted document
List<ObjectId> insertedIds = new ArrayList<>();
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asObjectId().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);

上述代码的输出类似于以下内容

Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]

有关本节中提到的方法和类的更多信息,请参阅以下资源

执行插入操作有三种方式,但我们专注于两种

  • insertOne() 方法用于插入单个文档。

  • insertMany() 方法用于插入多个文档。

如果您的文档中省略了该字段,这两种方法都会自动生成一个 _id

如果插入成功,这两种方法都会返回一个表示每个新文档 _id 的实例。

返回

写入