我有这个:
{
"_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
"Name" : "Categories",
"categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
"name" : "SubCategory",
"sub-categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
"name" : "SubSubCategory",
"standards" : []
}]
}]
}
我想使用 C# 驱动程序添加一个新的 SubCategory.有没有最佳的方法来做到这一点?
I would like to add a new SubCategory using the C# driver. Is there an optimal way to do this?
您可以使用 FindOneAndUpdateAsync
和位置运算符来做到这一点
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);
}
这篇关于将元素插入到MongoDB中的嵌套数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!