Insert a Document
You can insert a single document into a collection using the insertOne()
method on a MongoCollection
object. To insert a document, construct a
Document
object that contains the fields and values that you want to
store. If you call the insertOne()
method on a collection that does
not exist yet, the server automatically creates it for you.
Upon a successful insertion, insertOne()
returns an instance of
InsertOneResult
. You can retrieve information such as the _id
field of the document you inserted by calling the getInsertedId()
method on the InsertOneResult
instance.
If your insert operation fails, the driver raises an exception. For more
information on the types of exceptions raised under specific conditions,
see the API documentation for insertOne()
, linked at the bottom of
this page.
Example
The following snippet inserts a single document into the movies
collection.
Note
This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.
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 { InsertOneResult result = collection.insertOne(new Document() .append("_id", new ObjectId()) .append("title", "Ski Bloopers") .append("genres", Arrays.asList("Documentary", "Comedy"))); System.out.println("Success! Inserted document id: " + result.getInsertedId()); } catch (MongoException me) { System.err.println("Unable to insert due to an error: " + me); } } } }
When you run the example, you should see output that resembles the following
with the inserted document's ObjectId
in the value field:
Inserted document id: BsonObjectId{value=...}
Tip
Legacy API
If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.
For additional information on the classes and methods mentioned on this page, see the following API Documentation: