Andrew Reyes
Andrew Reyes

Reputation: 162

C# MongoDB Driver: How to insert a new subdocument into an existing document

Docoument structure

public class Document:
{
   [BsonRepresentation(BsonType.ObjectId)]
   public String _id { get; set; }
   [BsonIgnoreIfNull]
   public List<Event> Events { get; set; }
}

public class Event
{
   [BsonRepresentation(BsonType.ObjectId)]
   public String _id { get; set; }
   [BsonIgnoreIfNull]
   public String Title { get; set; }
}

I would like to insert a new subdocument 'Event' into an existing Document using Document._id. How could I do that in csharp?

Upvotes: 2

Views: 1883

Answers (1)

Mahdi
Mahdi

Reputation: 3349

You can do it like follows:

var id = ObjectId.Parse("5b9f91b9ecde570d2cf645e5"); // your document Id
var builder = Builders<MyCollection>.Filter;
var filter = builder.Eq(x => x.Id, id);
var update = Builders<MyCollection>.Update
    .AddToSet(x => x.Events, new MyEvent
    {
        Title = "newEventTitle",
        Id = ObjectId.GenerateNewId()
    });
var updateResult = await context.MyCollection.UpdateOneAsync(filter, update);

I changed your class names a bit, like this:

public class MyCollection
{
    public ObjectId Id { get; set; }
    public List<MyEvent> Events { get; set; }
}

public class MyEvent
{
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}

since I thought Document and Event were not good names but you can change them back. Also, note that the type of Id property is ObjectId and not string.

Upvotes: 4

Related Questions