Insert Documents
On this page
Overview
In this guide, you can learn how to use the MongoDB .NET/C# Driver to add documents to a MongoDB collection by performing insert operations.
An insert operation inserts one or more documents into a MongoDB collection. The .NET/C# Driver provides the following methods to perform insert operations, each of which has an asynchronous and synchronous version:
InsertOneAsync()
orInsertOne()
InsertManyAsync()
orInsertMany()
Tip
Interactive Lab
This page includes a short interactive lab that demonstrates how to
insert data by using the InsertOneAsync()
method. You can complete this
lab directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.
Sample Data
The examples in this guide use the restaurants
collection
from the sample_restaurants
database. The documents in this
collection use the following Restaurant
, Address
, and GradeEntry
classes as models:
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [ ] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
Note
The documents in the restaurants
collection use the camel-case naming
convention. The examples in this guide use a ConventionPack
to deserialize the fields in the collection into Pascal case and map them to
the properties in the Restaurant
class.
To learn more about custom serialization, see Custom Serialization.
This collection is from the sample datasets provided by Atlas. See the Quick Start to learn how to create a free MongoDB cluster and load this sample data.
The _id
Field
In a MongoDB collection, each document must contain an _id
field
with a unique field value.
MongoDB allows you to manage this field in two ways:
You can set this field for each document yourself, ensuring each
_id
field value is unique.You can let the driver automatically generate unique
ObjectId
values for each document_id
. If you do not manually set an_id
field value for a document, the driver will populate the field with anObjectId
.
Unless you can guarantee uniqueness, MongoDB recommends
you let the driver automatically generate _id
values.
Note
Duplicate _id
values violate unique index constraints, which
causes the driver to return a MongoWriteException
from
InsertOne()
or a MongoBulkWriteException
from
InsertMany()
.
To learn more about the _id
field, see the Server Manual Entry on
Unique Indexes.
To learn more about document structure and rules, see the Server Manual Entry on Documents.
Insert One Document
The following code shows how to use the asynchronous
InsertOneAsync()
method or the synchronous InsertOne()
method to
insert one document.
await _restaurantsCollection.InsertOneAsync(document);
_restaurantsCollection.InsertOne(document);
Insert Multiple Documents
The following code shows how to use the asynchronous
InsertManyAsync()
method or the synchronous InsertMany()
method to
insert multiple documents.
await _restaurantsCollection.InsertManyAsync(docs);
_restaurantsCollection.InsertMany(docs);
Tip
Find runnable examples using these methods under additional information.
Modify Insert Behavior
The InsertOne()
method takes the document you seek to insert as a
parameter. The InsertMany()
method takes an IEnumerable
collection of documents, such as a list or array, as a parameter.
The InsertOne()
method optionally takes a InsertOneOptions
type as an additional parameter,
which represents options you can use to configure the insert operation.
If you don't specify any InsertOneOptions
properties, the driver does
not customize the insert.
The InsertOneOptions
type allows you to configure options with the
following properties:
Property | Description |
---|---|
BypassDocumentValidation | Gets or sets a value indicating whether to bypass document
validation. If true , allows the write to opt-out of
document level validation. |
Comment | Gets or sets the comment for the operation. See the insert command
fields
for more information. |
The InsertMany()
method optionally takes a InsertManyOptions
type as an additional parameter, which has the preceding
BypassDocumentValidation
and Comment
properties and the
additional IsOrdered
property:
Property | Description |
---|---|
IsOrdered | Gets or sets a value indicating whether the requests are
fulfilled in order. If true , the driver sends documents to the
server in the order provided. If an error occurs, the driver
and server abort all remaining insert operations.
To learn more, see Ordered Behavior.Default: true |
Example
The following code uses the InsertMany()
method to insert four new
Restaurant
documents into a collection with
BypassDocumentValidation
set to true
:
var restaurantsList = new List<Restaurant>() { new() { Name = "Été Bleu", Cuisine = "French" }, new() { Name = "Lucky Bird", Cuisine = "Café/Coffee/Tea" }, new() { Name = "Wildflower Café", Cuisine = "Vegetarian" }, new() { Name = "Blue Moon Grill", Cuisine = "American" }, }; var options = new InsertManyOptions() { BypassDocumentValidation = true }; Console.WriteLine("Inserting documents..."); _restaurantsCollection.InsertMany(restaurantsList, options);
The InsertMany()
method has no return value. You can verify that
your documents were successfully inserted by executing a Find()
operation on the collection. For an example on how to find a document,
see Find a Document.
Specify Ordered Behavior
Assume you want to insert the following documents:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" } { "_id" : 1, "name" : "Restaurant C" } { "_id" : 3, "name" : "Restaurant D" }
If you attempt to insert these documents with default
InsertManyOptions
, the driver throws a MongoBulkWriteException
at the third
document because of the repeated _id
value, but the documents before
the error-producing document are still inserted into your collection.
If you look inside your collection, you should be able to see the following documents:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" }
If you set IsOrdered
to false
in your insert operation, the driver will
continue to insert your documents even if some documents produce errors.
With this modified insert behavior, the driver throws an exception but inserts all documents
that do not produce errors.
If you look inside your collection, you should be able to see the following documents:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" } { "_id" : 3, "name" : "Restaurant D" }
Additional Information
For runnable examples of the insert operations, see the following usage examples:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: