在 MongoDB 的嵌套文档中插入新文档

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; }

}

现在数据显示如下。

我正在尝试在 Technology 中添加 ProductGroup(这是一个 BsonDocument 集合)集合。

将您的技术模型更改为

[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);

@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);
  1. 尽可能使用通用类型。因为这段代码 parent["ProductGroups"] 对于任何重构来说都是危险的地方。
  2. 您的任务可以在一次查询中完成

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);