Insert Documents
On this page
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
_id
field 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 MongoDB, each document must contain a unique _id
field.
MongoDB allows you to manage this field in the following ways:
Manage this field yourself, ensuring that each
_id
value you set is unique.Let the driver automatically generate unique
ObjectId
values. The driver generates a uniqueObjectId
value for each document if you do not specify a value for the_id
field when performing an insert.
Unless you provide strong guarantees for uniqueness, we recommend that
you let the driver automatically generate _id
values for your
documents.
Important
Duplicate _id Values
If you attempt to perform a write operation that includes duplicate _id
values, the duplicate 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.
Upon successful insertion, the method returns an
InsertOneResult
instance that contains the _id
of the 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, None).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
constructing and passing an InsertOneOptions
struct.
Note
Instantiating Options
The Rust driver implements the Builder design pattern for the
creation of many different types, including InsertOneOptions
.
You can use each type's builder()
method to construct an options
instance by chaining option builder functions one at a time.
The following table describes the options available in InsertOneOptions
:
Option | Description |
---|---|
| 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 |
| 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 |
| 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 construct an InsertOneOptions
instance:
let _opts = InsertOneOptions::builder() .bypass_document_validation(true) .build();
Insert Multiple Documents
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.
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, None).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
constructing and passing an InsertManyOptions
struct. The
following table describes the options available in
InsertManyOptions
:
Option | Description |
---|---|
| 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 |
| 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 |
| 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 |
| 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 construct an InsertManyOptions
instance:
let _opts = InsertManyOptions::builder() .comment(Some("hello world".into())) .build();
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 of the ordered
option in your InsertManyOptions
:
If
ordered
istrue
(the default value), the driver throws aBulkWriteError
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 set
ordered
tofalse
, the driver still throws aBulkWriteError
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() } ]; let opts = InsertManyOptions::builder().ordered(false).build(); my_coll.insert_many(docs, opts).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: