![](/img/trans.png)
[英]how to concurrently insert a new document into a collection in MongoDB 4 with .net driver 2.7.3
[英]Insert new document in nested documents in MongoDB
我是MongoDB的初學者。 請在下面查看我的模型。
public class Technology
{
public Technology()
{
ProductGroups = new List<ProductGroup>();
}
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId _id { get; set; }
public string Name { get; set; }
public IEnumerable<ProductGroup> ProductGroups { get; set; }
}
public class ProductGroup
{
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId _id { get; set; }
public string Name { get; set; }
}
現在數據顯示如下。
我嘗試添加ProductGroup
(這是一個BsonDocument集合)中收集Technology
。
將您的技術模型更改為
[BsonElementAttribute("productgroups")]
public IList<ProductGroup> ProductGroups{ get; set; }
然后,
var productGroup = new BsonDocument().Add("_id", productGroup_id).Add("Name", name);
var technologies = database.GetCollection("technology");
var technology = technologies.FindOneById(ObjectId.Parse(technology_id));
technology["productgroups"] = new BsonArray().Add(BsonValue.Create(productGroup));
technologies.Save(technology);
parent["ProductGroups"]
對於任何重構都是危險的地方。 var productGroup = new ProductGroup { Id = ObjectId.GenerateNewId(), Name = model.Name };
var collection = database.GetCollection<Technology>("Technology");
var update = Builders<Technology>.Update.AddToSet(x => x.ProductGroups, productGroup);
await collection.FindOneAndUpdateAsync(x => x.Id == model._id, update);
@CodingDefined我按照v2.0.1.27更改了代碼
請在下面查看我的代碼。 非常感謝您的幫助。
var productGroup = new BsonDocument()
.Add("_id", ObjectId.GenerateNewId())
.Add("Name", model.Name);
BsonDocument parent = null;
var _parent = Collection.FindOneByIdAs(typeof(BsonDocument), model._id);
if (_parent != null)
{
parent = _parent.ToBsonDocument();
parent["ProductGroups"] = new BsonArray().Add(BsonValue.Create(productGroup));
Collection.Save(parent);
}
請確保新的子記錄沒有清除現有記錄
parent["ProductGroups"] = parent["ProductGroups"].AsBsonArray.Add(productGroup);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.