Insert documents
Last updated
Last updated
You can insert a document using the InsertOne
method on a IMongoCollection<T>
reference.
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 Use
r document in collection.
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.
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
The sample inserts 10 User
documents in the collection.
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