本文介紹了將元素插入到MongoDB中的嵌套數組中的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我有這個:
{
"_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中的嵌套數組中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!