Docs Menu
Docs Home
/ / /
C#/.NET
/

Insert a Document

On this page

  • Example
  • Expected Result
  • Additional Information
  • API Documentation

You can insert a single document into a collection by using the synchronous InsertOne() method, or the asynchronous InsertOneAsync() method.

The following example inserts a document into the restaurants collection.

Select the Asynchronous or Synchronous tab to see the corresponding code.

// Generates a new restaurant document
Restaurant newRestaurant = new()
{
Name = "Mongo's Pizza",
RestaurantId = "12345",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Asynchronously inserts the new document into the restaurants collection
await _restaurantsCollection.InsertOneAsync(newRestaurant);

For a fully runnable example of the InsertOneAsync() operation, see the Asynchronous Insert One Example.

// Generates a new restaurant document
Restaurant newRestaurant = new()
{
Name = "Mongo's Pizza",
RestaurantId = "12345",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Inserts the new document into the restaurants collection
_restaurantsCollection.InsertOne(newRestaurant);

For a fully runnable example of the InsertOne() operation, see the Synchronous Insert One Example.

After running either of the preceding full examples, the InsertOne() method inserts the document, and the Find() method returns the newly inserted document. The output is similar to the following:

Inserting a document...
Document Inserted: { "_id" : ObjectId("..."), "name" : "Mongo's Pizza", "restaurant_id" : "12345", "cuisine" : "Pizza", "address" : { "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { "street" : "Pizza St", "zipcode" : "10003" } }, "borough" : "Manhattan", "grades" : [{ "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { } }] }

To learn more about using builders, see Operations with Builders.

Back

Find Multiple Documents