Upserting in Mongo DB using official C# driver

mongodb c# connection best practices
mongodb c# driver
mongodb c# driver compatibility
how to insert data in mongodb using c#
c# mongodb example
mongodb c# get all documents in collection
how to connect mongodb using c#
c# mongodb insert bsondocument

In the official documentation of mongodb they mention upserts, so it would be really nice to write an upsert command instead of:

if (_campaignRepo.Exists(camp))


something which would implement that logic on the db level if it is possible. So what is the way to do an upsert if there is one?

The following code is from a working app:

    Query.EQ("weekNumber", week),

The weekplanStore is my MongoDB collection, and the code will update the document found with the query in the first argument or insert a new one if none is found. The "trick" is to use the UpdateFlags.Upsert modifier.

The rawWeekPlan is the object inserted or updated, and has the following type:

private class RawWeekPlan
    public ObjectId id;
    public int weekNumber;
    public WeekPlanEntry[] entries;

and turned into bson by the driver automatically.

Working with MongoDB in .NET (Part 1): Driver Basics & Inserting , MongoDB drivers allows you to work with MongoDB from different programming language. In this tutorial series, we'll be working with the C#  Download MongoDB Official C# Driver. This is the place where you can obtain the source code and download the setup package. When you download a proper package and install it, you will be able to find the following two assembly files under the path Program Files Folder\MongoDB\CSharpDriver 1.2 .

Version 2 of the MongoDB C# driver requires setting the IsUpsert flag in the write commands. This example will upsert an entire document.

var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } };
var result = await collection.ReplaceOneAsync(
                filter: new BsonDocument("_id", 123),
                options: new ReplaceOptions { IsUpsert = true },
                replacement: newDoc);

Version 1 of the MongoDB C# driver implements this logic within the Save command.

var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } };

The Save method is a combination of Insert and Update. If the Id member of the document has a value, then it is assumed to be an existing document and Save calls Update on the document (setting the Upsert flag just in case it actually is a new document after all). Otherwise it is assumed to be a new document and Save calls Insert after first assigning a newly generated unique value to the Id member.


Note: This does require the proper mapping of the Id field however. More info on that here:

C# MongoDB tutorial - programming MongoDB in C#, C# MongoDB insert document. A new document is inserted into the collection with the InsertOne() method. Program.cs. using MongoDB.Driver;  NuGet is the simplest way to get the driver. Use MongoDB.Driver for all new projects. For more information, see Installation.

Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.

The currently recommended way to upsert a document is by calling and awaiting ReplaceOneAsync with the IsUpsert flag turned on and a filter that matches the relevant document:

Hamster hamster = ...
var replaceOneResult = await collection.ReplaceOneAsync(
    doc => doc.Id == hamster.Id, 
    new UpdateOptions {IsUpsert = true});

You can check whether the operation was an insert or an update by looking at ReplaceOneResult.MatchedCount:

Quick Start: C# and MongoDB, Driver from NuGet to establish a connection to a MongoDB server. In the case of this blog series, I'm using C# to connect to a MongoDB Atlas  This document reflects an unreleased version of the C# Driver and the 2.3/2.4 subscriber edition of MongoDB, which is currently a release candidate. This page is a brief overview of authenticating to a MongoDB cluster with the MongoDB C# Driver using version 1.8 and above.

You can use the regular update command, but just pass it the Upsert update flag

MongoCollection collection = db.GetCollection("matches");
var query = new QueryDocument("recordId", recordId);

var update = Update.Set("FirstName", "John").Set("LastName","Doe");
matchCollection.Update(query, update, UpdateFlags.Upsert, SafeMode.False);

That code is adapted from a working application (shortened for clarity)

Working with MongoDB Transactions with C# and the .NET Framework, C# applications connected to a MongoDB database use the MongoDB . NET driver to your Visual Studio Application, in the NuGet Package that will insert some sample data into MongoDB then update the prices for all  I have a problem while upserting to mongo db using the official C# driver. public abstract class AggregateRoot { /// <summary> /// All mongoDb documents must have an id, we specify i

Create a web API with ASP.NET Core and MongoDB, NET Core web API using a MongoDB NoSQL database. Define a schema for the Books collection and insert two documents using the following command: C# Copy. using BooksApi.Models; using MongoDB.Driver; using System. Per the official Mongo Client reuse guidelines, MongoClient should be  In the last edition of this C# Quick Start for MongoDB CRUD operations, we explored some of the different ways to Read data. We saw how to add filters to our query and how to sort the data. This post is about the Update operation and how the C# driver's Update and MongoDB work together to accomplish this important task.

Driver Tutorial, This tutorial introduces the officially supported C# Driver for MongoDB. which is useful for handling optional elements when creating BsonDocuments using  This is the official MongoDB Go Driver. Installation¶ The recommended way to get started using the MongoDB Go driver is ← MongoDB C#/.NET Driver Java

Using MongoDB with the Official C# Driver, Insertion. Adding new documents is much simple as editing them. You create a reference for the collection, create a new BsonDocument , and  MongoDB C# Driver. You can get the latest stable release from the official feed or from our github releases page. If you'd like to work with the bleeding edge, you can use our custom feed. Some packages on this feed are pre-release and, while they've passed all our tests, are not yet ready for production. Getting Started Untyped Documents

  • Does it work for nested collections? Have you tried it out? Because it does not work for them in my case
  • This is no longer possible with the new API.
  • Updated. Although I think the new API made the upsert commands harder to use.
  • What gets passed to the filter if the newDocs ID is null, i.e. it's an insert? Just an empty bson document?
  • @BenCr if you're just doing a normal insert instead of an upsert then you should use the InsertOneAsync method. This doesn't require the ID field to be specified as MongoDB will create one during insert, but you can also create these IDs without going to the database just like a GUID so it's up to you. More info in the C# driver documentation here:…
  • I am trying to use ReplaceOneAsync but it throws an exception :"Element name ' 'is not valid ", i am using the filter for updateOneasync it works but not with replaceone . can you please help me?
  • UpdateOptions is obselete, use new ReplaceOptions {IsUpsert = true}); now