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

Notice how overwhelming querying using BsonDocument can be. And it's not only that you have to carefully type all these in curly brackets, it is also dangerous that you might end up having wrong type of data in the database because MongoDB will use default data types for values that their type haven't explicitly defined.

β›” Building the documents manually or using the Parse method is not recommended

Luckily, there is the ToBsonDocument helper method that builds the BsonDocument from your typed class automatically and saves you from all the trouble.

var personsBsonCollection = database
    .GetCollection<BsonDocument>(Constants.UsersCollection);

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

await personsBsonCollection
    .InsertOneAsync(appPerson.ToBsonDocument());

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.

Prefer this method when you need to add multiple documents, instead looping the array and calling the InsertOne method. InsertMany is more efficient since you avoid making round trips to the database

IMongoCollection<T>
    .InsertMany(IEnumerable<T> documents)

The sample inserts 10 User documents in the collection.

InsertDocuments.cs
// generate 10 users
var persons = RandomData.GenerateUsers(10);

// Insert multiple documents
await personsCollection.InsertManyAsync(persons);

Notice that insert operations return the inserted Id(s) as part of the result. This way, the driver automatically updates the Id field on the argument(s) passed on the update operation

Last updated