我有这个 :
{
"_id" : ObjectId("4fb4fd04b748611ca8da0d48"),"Name" : "Categories","categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d46"),"name" : "SubCategory","sub-categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d47"),"name" : "SubSubCategory","standards" : []
}]
}]
}
我想使用C#驱动程序添加一个新的SubCategory.有最佳方法吗?
解决方法
您可以使用FindOneAndUpdateAsync和位置运算符执行此操作
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);
}