文件结构
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中做到这一点?
您可以按照以下步骤进行操作:
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
and not string
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句