Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element into nested array in Mongodb

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?

like image 268
Uokimi Uokimi Avatar asked Jun 09 '15 12:06

Uokimi Uokimi


People also ask

How do I add elements to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I push into nested array?

After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested ...

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.

Can we insert array in MongoDB?

MongoDB Array of Objects using insert() with ExampleThe “insert” command can also be used to insert multiple documents into a collection at one time. The below code example can be used to insert multiple documents at a time. The output shows that those 3 documents were added to the collection.


1 Answers

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);
}
like image 190
rnofenko Avatar answered Sep 28 '22 18:09

rnofenko