【问题标题】:C# MongoDB Driver: How to insert a new subdocument into an existing documentC# MongoDB 驱动程序:如何将新的子文档插入到现有文档中
【发布时间】:2018-09-14 09:36:10
【问题描述】:
文档结构
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; }
}
我想使用 Document._id 将新的子文档“事件”插入到现有文档中。我怎么能在 csharp 中做到这一点?
【问题讨论】:
标签:
mongodb
mongodb-query
mongodb-.net-driver
【解决方案1】:
你可以这样做:
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);
我稍微更改了你的班级名称,如下所示:
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; }
}
因为我认为 Document 和 Event 不是好名字,但您可以将它们改回来。
另外,请注意Id 属性的类型是ObjectId 而不是string。