我是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
中添加Technology
(它是一个BsonDocument Collection)集合。
答案 0 :(得分:2)
将您的技术模型更改为
[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);
答案 1 :(得分:2)
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);
答案 2 :(得分:1)
@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);