I have the following classes:
class Parent
{
public ObjectId Id { get; set; }
[BsonDictionaryOptions(Representation = DictionaryRepresentation.ArrayOfDocuments)]
public IDictionary<string, List<Child>> Children { get; set; }
}
class Child { }
I know want to add a new Child in one of the entries of the Dictionary:
using MongoDB.Driver;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var collection = new MongoClient("mongodb://localhost:27017")
.GetDatabase("Test").GetCollection<Parent>("Parents");
var parent = new Parent();
collection.InsertOne(parent);
collection.UpdateOne(p => p.Id == parent.Id,
Builders<Parent>.Update.Push(p => p.Children["string1"], new Child()));
}
}
}
I get a System.InvalidOperationException:
Unable to determine the serialization information for p => p.Children.get_Item("string1").
I managed to get it to work like this:
collection.UpdateOne(p => p.Id == parent.Id && p.Children.Any(a => a.Key == "string1"),
Builders<Parent>.Update.Push($"{nameof(Parent.Children)}.$.v", new Child()));
But this is super ugly and only works if the entry "string1" already exists.
This might be related: Unable to determine the serialization information for the expression error