简体   繁体   中英

Insert new document in nested documents in MongoDB

I am a beginner in MongoDB. Please see my models below.

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

}

Now the data shows like below.

在此处输入图片说明

I am try to add the ProductGroup ( it's a BsonDocument Collection) collection in Technology .

Change your Model of Technology as

[BsonElementAttribute("productgroups")]
public IList<ProductGroup> ProductGroups{ get; set; }

Then,

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. Use generic types where you can. Because this code parent["ProductGroups"] is dangerous place for any refactoring.
  2. Your task can be done in one query

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 I change my code as per the v2.0.1.27

Please see my code below. Thank you very much for your help.

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

}

Please make sure, the new child record is not clearing the existing records

parent["ProductGroups"] = parent["ProductGroups"].AsBsonArray.Add(productGroup);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM