Docs 菜单

插入操作

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

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

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

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

注意

插入操作中的 id_ 字段

插入文档时, MongoDB默认对文档实施一项默认:每个文档必须包含唯一的 _id 值。重复的 _id 值违反了唯一索引约束,导致 WriteError

管理该字段有两种方法:

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

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

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

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

如果要插入单个文档,请使用 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]

注意

设置示例

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 moviessample_mflix数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。

以下代码是一个完整的独立运行文件,用于执行插入一个操作和插入多个操作:

// Inserts a sample document describing a movie by using the Java driver
package org.example;
import java.util.Arrays;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.InsertManyResult;
import java.util.List;
public class Insert {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// Inserts a sample document describing a movie into the collection
InsertOneResult result = collection.insertOne(new Document()
.append("_id", new ObjectId())
.append("title", "Ski Bloopers")
.append("genres", Arrays.asList("Documentary", "Comedy")));
// Prints the ID of the inserted document
System.out.println("Inserted document id - insert one: " + result.getInsertedId());
// Creates two sample documents containing a "title" field
List<Document> movieList = Arrays.asList(
new Document().append("title", "Short Circuit 3"),
new Document().append("title", "The Lego Frozen Movie"));
// Inserts sample documents describing movies into the collection
InsertManyResult result = collection.insertMany(movieList);
// Prints the IDs of the inserted documents
System.out.println("Inserted document id - insert many: " + result.getInsertedIds());
}
}
}
insertOne() document id: BsonObjectId{value=...}
insertMany() document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}

有关用于插入文档的方法和类的更多信息,请参阅以下API文档: