Insert documents

Insert one document

You can insert a document using the InsertOne method on a IMongoCollection<T> reference.

IMongoCollection<T>.InsertOne(<document>)

Depending on the collection type you can pass either your own class type or a BsonDocument. You can build the BsonDocument either manually or using the BsonDocument.Parse method.

The sample insert a User document in collection.

InsertDocuments.cs
var database = Client
    .GetDatabase(Constants.SamplesDatabase);

var personsCollection = database
    .GetCollection<User>(Constants.UsersCollection);

User appPerson = RandomData.GenerateUsers(1).First();

// Insert one document
await personsCollection.InsertOneAsync(appPerson);
triangle-exclamation

Insert many documents

To add multiple documents at once, you can use the InsertMany collection method, passing the array of items to be inserted in the collection.

circle-check

The sample inserts 10 User documents in the collection.

circle-check

Last updated