Docs 菜单
Docs 主页
/ / /
Java (Sync) 驱动程序
/ / /

插入操作

在此页面上

  • 概述
  • 关于以下项的说明: _id
  • 插入单一文档
  • 插入多个文档
  • 总结

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

您可以使用 MongoDB 检索、更新和删除信息。要执行任何这些操作,用户配置文件和订单等信息需要存在于 MongoDB 中。要使该信息存在,请首先执行插入操作。

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

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

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

管理该字段有两种方法:

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

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

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

注意

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

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

如果要插入单个文档,请使用 insertOne() 方法。

成功插入后,该方法将返回一个InsertOneResult 实例,该实例表示新文档的_id

以下示例使用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 }

成功插入后,该方法会返回一个InsertManyResult实例,表示每个新文档的_id

以下示例创建两个文档并将其添加到List中,并使用insertMany()方法插入List

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的实例。

后退

写入操作

来年

删除文档