“文档” 菜单
文档首页
/ / /
Java (Sync) 驱动程序
/ /

插入文档

您可以使用 MongoCollection 对象上的insertOne()方法,将单个文档插入集合中。要插入文档,请构建一个 Document 对象,其中包含待存储的字段和值。若对一个尚不存在的集合调用 insertOne() 方法,服务器会自动创建该集合。

成功插入后,insertOne() 会返回 InsertOneResult 的实例。您可以通过对 InsertOneResult 实例调用 getInsertedId() 方法来检索信息,例如所插入文档的 _id 字段。

如果插入操作失败,驱动程序会引发异常。 有关特定条件下引发的异常类型的更多信息,请参阅本页底部链接的insertOne()的 API 文档。

以下代码片段用于在 movies 集合中插入单个文档。

注意

此示例使用连接 URI 连接到 MongoDB 实例。要了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南。

// Inserts a sample document describing a movie by using the Java driver
package usage.examples;
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;
public class InsertOne {
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");
try {
// 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("Success! Inserted document id: " + result.getInsertedId());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to insert due to an error: " + me);
}
}
}
}

运行该示例时,应看到类似于以下内容的输出,其中“值”字段中包含插入文档的 ObjectId

Inserted document id: BsonObjectId{value=...}

提示

旧版 API

如果您使用的是传统 API,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

有关此页面上提及的类和方法的更多信息,请参阅以下 API 文档:

  • insertOne()

  • 文档

  • InsertOneResult

← 插入操作