Docs Menu
Docs Home
/ / /
Rust Driver
/ / /

Insert Documents

On this page

  • Overview
  • The _id Field
  • Insert a Document
  • Example
  • Modify insert_one Behavior
  • Insert Multiple Documents
  • Example
  • Modify insert_many Behavior
  • Ordered Behavior Example
  • Additional Information
  • API Documentation

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 document

  • insert_many() to insert one or more documents

This guide includes the following sections:

  • The _id Field describes the _id field that each document contains

  • Insert 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

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.

Use the insert_one() method to insert a single document into a collection.

Upon successful insertion, the method returns an InsertOneResult instance that contains the _id of the inserted document.

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);

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.

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
bypass_document_validation
If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see the guide on Schema Validation.

Type: bool
Default: false
write_concern
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.

Type: WriteConcern
comment
An arbitrary Bson value tied to the operation to trace it through the database profiler, currentOp, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Bson
Default: None

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?;

Use the insert_many() method to insert multiple documents into a collection.

Upon successful insertion, the method returns an InsertManyResult instance that contains the _id values of the inserted documents.

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);
}

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.

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
bypass_document_validation
If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see the guide on Schema Validation.

Type: bool
Default: false
ordered
If true, when any insert fails, the operation returns without inserting the remaining documents. If false, even if an insert fails, the operation continues with the remaining writes. To learn more about ordered inserts, see the Ordered Behavior Example section of this guide.

Type: bool
Default: true
write_concern
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.

Type: WriteConcern
comment
An arbitrary Bson value tied to the operation to trace it through the database profiler, currentOp, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Bson
Default: None

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?;

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 a BulkWriteError when it attempts to insert the document with the duplicate _id value. However, the driver still inserts the documents before the error occurs.

  • If you pass a value of false, the driver still throws a BulkWriteError when it attempts to insert the document with the duplicate _id value, 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: 4, 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" }

For runnable examples of the insert operations, see the following usage examples:

To learn more about the methods and types mentioned in this guide, see the following API documentation:

Back

Write Operations

Next

Modify Documents