Insert element into nested array in Mongodb

Uokimi Uokimi picture Uokimi Uokimi · Jun 9, 2015 · Viewed 9.7k times · Source

I have this :

{
  "_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
  "Name" : "Categories",
  "categories" : [{
      "_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
      "name" : "SubCategory",
      "sub-categories" : [{
          "_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
          "name" : "SubSubCategory",
          "standards" : []
        }]
    }]
}

I would like to add a new SubCategory using the C# driver. Is there an optimal way to do this?

Answer

rnofenko picture rnofenko · Jun 9, 2015

You can do this using FindOneAndUpdateAsync and positional operator

public async Task Add(string productId, string categoryId, SubCategory newSubCategory)
{
    var filter = Builders<Product>.Filter.And(
         Builders<Product>.Filter.Where(x => x.Id == productId), 
         Builders<Product>.Filter.Eq("Categories.Id", categoryId));
    var update = Builders<Product>.Update.Push("Categories.$.SubCategories", newSubCategory);
    await collection.FindOneAndUpdateAsync(filter, update);
}