Ragesh Puthiyedath Raju
Ragesh Puthiyedath Raju

Reputation: 3939

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.

enter image description here

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

Upvotes: 2

Views: 3062

Answers (3)

rnofenko
rnofenko

Reputation: 9533

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

Upvotes: 3

Ragesh Puthiyedath Raju
Ragesh Puthiyedath Raju

Reputation: 3939

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

Upvotes: 1

CodingDefined
CodingDefined

Reputation: 2132

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

Upvotes: 2

Related Questions