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?
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.
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 ...
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With