Search code examples
c#mongodbbson

Add to child BsonDocument


I have the following. It works.

  private static async Task AddAndUpdateNestedDocument(IMongoCollection<BsonDocument> collection)
  {
      var key = "bert";
      var filter = Builders<BsonDocument>.Filter.Exists(key);
      await collection.DeleteManyAsync(filter);
      var subkey = "friend";
      var document = new BsonDocument(key, new BsonDocument(subkey, "ernie"));
      await collection.InsertOneAsync(document);
      var updater = Builders<BsonDocument>.Update.Set("sesame", "street");
      await collection.UpdateOneAsync(filter, updater);
  }

This runs without error. When I fetch the resulting document, it looks like this:

{ "_id" : ObjectId("5ef62acf152cc17a1c139f6d"), "bert" : { "friend" : "ernie" }, "sesame" : "street" }

That's all fine, but what I really wanted to do to have the update command insert "sesame" and "street" inside of the "bert" sub-document, so that it ends up like this:

{ "_id" : ObjectId("5ef62acf152cc17a1c139f6d"), "bert" : { "friend" : "ernie", "sesame" : "street" } }

How can I do that?


Solution

  • For nested fields you can use the dot notation:

    Builders<BsonDocument>.Update.Set(key + ".sesame", "street");