Bob Horn
Bob Horn

Reputation: 34297

Adding a New Subdocument in MongoDB

I'm trying to add a subdocument to a list in an existing document. The documents look like this:

public class EtaMembershipDocument : DocumentBase
{
    public List<EtaAssociationDocument> EtaAssociatonDocuments { get; set; }
}

I'm at a loss as to how to add a new EtaAssociationDocument to the list using C# and MongoDB. This is my latest attempt:

var collection = this.DataStore.GetCollection<EtaMembershipDocument>(EtaMembershipsCollectionName);

Update.AddToSet("EtaAssociationDocuments", BsonValue.Create(etaAssociationDocument));

On that last line, I get this error:

.NET type EtaAssociationDocument cannot be mapped to a BsonValue.

The problem is that I don't even know if this is how I'm supposed to add a subdocument in the first place. If my approach is correct, what can I do to resolve the error? If my approach is incorrect, how should I be doing this?

Upvotes: 2

Views: 2153

Answers (1)

mnemosyn
mnemosyn

Reputation: 46301

The question is a duplicate, but since the original question is quite old, its answer is kind of outdated. You no longer have to meddle with manual conversion to BsonDocument. Instead, you can use the strongly-typed helpers, which is quite helpful for refactoring:

collection.Update(
    Query<EtaMembershipDocument>.EQ(p => p.Id, someId),
    Update<EtaMembershipDocument>.AddToSet
        (p => p.EtaAssociatonDocuments, documentToAdd));

Unlike PushWrapped and ToBsonDocument, this will ensure that the set you are referring to implements IEnumerable<T> and that documentToAdd is of the same type as the type parameter T of the IEnumerable<T>.

Upvotes: 3

Related Questions