Overview
In this guide, you can learn how to insert documents into a MongoDB collection.
Before you can find, update, and delete any documents in MongoDB, you need to insert them. You can insert documents by using the following methods:
insert_one()to insert one documentinsert_many()to insert one or more documents
This guide includes the following sections:
The _id Field describes the
_idfield that each document containsInsert a Document describes how to use the driver to insert a single document into a collection
Insert Multiple Documents describes how to use the driver to insert multiple documents into a collection
Additional Information provides links to resources and API documentation for types and methods mentioned in this guide
The _id Field
In a MongoDB collection, each document must contain a unique _id field value. The driver automatically generates a unique value for each document as an ObjectId type when you insert data into a collection.
If you prefer to set custom values, you can assign the values in the _id fields of documents passed to your insert operation.
Important
Duplicate _id Values
If you attempt to insert documents that include duplicate _id values, these values violate unique index constraints and cause the write operation to fail.
To learn more about the _id field, see Unique Indexes in the Server manual.
To learn more about document structure and rules, see Documents in the Server manual.
Insert a Document
Use the insert_one() method to insert a single document into a collection.
You must insert a document of the same type that you parameterized your Collection instance with. For example, if you parameterized your collection with the MyStruct struct, pass a MyStruct instance as a parameter to the insert_one() method to insert a document. To learn more about specifying a type parameter, see the Collection Parameterization section of the Databases and Collections guide.
Upon successful insertion, the method returns an InsertOneResult type that contains the _id field of the newly inserted document.
Example
The following example uses the insert_one() method to insert a document into the books collection:
let my_coll: Collection<Book> = client.database("db").collection("books"); let doc = Book { _id: 8, title: "Atonement".to_string(), author: "Ian McEwan".to_string() }; let insert_one_result = my_coll.insert_one(doc).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
Tip
Nonexistent Databases and Collections
If a database and collection don't exist when you perform a write operation on them, the server automatically creates them.
Modify insert_one Behavior
You can modify the behavior of the insert_one() method by chaining option builder methods to insert_one(). These option builder methods set InsertOneOptions struct fields.
Note
Setting Options
You can set InsertOneOptions fields by chaining option builder methods directly to the insert_one() method call. If you're using an earlier version of the driver, you must construct an InsertOneOptions instance by chaining option builder methods to the builder() method. Then, pass your options instance as a parameter to insert_one().
The following table describes the options available in InsertOneOptions:
Option | Description |
|---|---|
| If |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. |
| An arbitrary |
The following code shows how to set the bypass_document_validation field by chaining the bypass_document_validation() method to the insert_one() method:
let _result = my_coll.insert_one(doc) .bypass_document_validation(true) .await?;
Full File Example: Insert One Document
This example inserts a document into the restaurants collection of the sample_restaurants database. The insert_one() method inserts a document that has name, borough, and cuisine field values.
You can insert this document as an instance of the Document type or a custom data type. To specify which data type represents the collection's data, perform the following actions on the highlighted lines:
To access and insert collection documents as BSON documents, replace the
<T>type parameter with<Document>and the<struct or doc>placeholder withinsert_doc.To access and insert collection documents as instances of the
Restaurantstruct, replace the<T>type parameter with<Restaurant>and the<struct or doc>placeholder withinsert_struct. TheRestaurantstruct is defined at the top of the code file.
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
use std::env; use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
use std::env; use mongodb::{ bson::{doc, Document}, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
Insert Multiple Documents
Use the insert_many() method to insert multiple documents into a collection.
Pass a vector containing one or more documents to the insert_many() method to insert them into your collection. These documents must be instances of the type that you parameterized your Collection instance with. For example, if you parameterized your collection with the MyStruct struct, pass a vector of MyStruct instances as a parameter to the insert_many() method.
Upon successful insertion, the method returns an InsertManyResult type that references the _id values of the inserted documents.
Example
The following example uses the insert_many() method to insert multiple documents into the books collection:
let docs = vec![ Book { _id: 5, title: "Cat's Cradle".to_string(), author: "Kurt Vonnegut Jr.".to_string() }, Book { _id: 6, title: "In Memory of Memory".to_string(), author: "Maria Stepanova".to_string() }, Book { _id: 7, title: "Pride and Prejudice".to_string(), author: "Jane Austen".to_string() } ]; let insert_many_result = my_coll.insert_many(docs).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{:?}", value); }
Inserted documents with _ids: Int32(5) Int32(6) Int32(7)
Tip
Nonexistent Databases and Collections
If a database and collection don't exist when you perform a write operation on them, the server automatically creates them.
Modify insert_many Behavior
You can modify the behavior of the insert_many() method by chaining option builder methods to insert_many(). These option builder methods set InsertManyOptions struct fields.
The following table describes the options available in InsertManyOptions:
Option | Description |
|---|---|
| If |
| If |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. |
| An arbitrary |
The following code shows how to set the comment field by chaining the comment() method to the insert_many() method:
let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) .await?;
Full File Example: Insert Multiple Documents
This example inserts multiple documents into the restaurants collection of the sample_restaurants database. The example inserts documents that have name and cuisine field values by passing a vector of documents to the insert_many() method.
You can insert these documents as instances of the Document type or a custom data type. To specify which data type represents the collection's data, perform the following actions on the highlighted lines:
To access and insert collection documents as BSON documents, replace the
<T>type parameter with<Document>and the<struct or doc>placeholder withinsert_docs.To access and insert collection documents as instances of the
Restaurantstruct, replace the<T>type parameter with<Restaurant>and the<struct or doc>placeholder withinsert_structs. TheRestaurantstruct is defined at the top of the code file.
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
use mongodb::{ bson::{doc, Document}, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).run()?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
Ordered Behavior Example
Assume you want to insert the following documents into the books collection:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 1, "title": "Blueberries for Sal" } { "_id": 3, "title": "Goodnight Moon" }
When you attempt to insert these documents, the result depends on the value passed to the ordered() option builder method:
If you pass a value of
true(the default value), the driver throws aBulkWriteErrorwhen it attempts to insert the document with the duplicate_idvalue. However, the driver still inserts the documents before the error occurs.If you pass a value of
false, the driver still throws aBulkWriteErrorwhen it attempts to insert the document with the duplicate_idvalue, but it inserts every other document.
The following code shows how to perform an unordered write operation to insert the preceding documents:
let docs = vec![ Book { _id: 1, title: "Where the Wild Things Are".to_string(), author: "".to_string() }, Book { _id: 2, title: "The Very Hungry Caterpillar".to_string(), author: "".to_string() }, Book { _id: 1, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; my_coll.insert_many(docs).ordered(false).await?;
Even though this operation results in a BulkWriteError, you can still find the non-error-producing documents in your collection:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 3, "title": "Goodnight Moon" }
Additional Information
For runnable examples of the insert operations, see the following usage examples:
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation: