C# MongoDB 驱动程序:如何将新的子文档插入现有文档
C# MongoDB Driver: How to insert a new subdocument into an existing document
文档结构
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 将新的子文档 'Event' 插入到现有文档中。我怎么能在 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);
我稍微更改了您的 class 名称,如下所示:
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
。
文档结构
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 将新的子文档 'Event' 插入到现有文档中。我怎么能在 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);
我稍微更改了您的 class 名称,如下所示:
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
。