将元素插入Mongodb中的嵌套数组中
我有这个 :
{ "_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.Filter.And( Builders .Filter.Where(x => x.Id == productId), Builders .Filter.Eq("Categories.Id", categoryId)); var update = Builders .Update.Push("Categories.$.SubCategories", newSubCategory); await collection.FindOneAndUpdateAsync(filter, update); }
为我的案例添加一个例子。 在进入数组内部时工作但没有美元符号:
public async Task AddCustomMetadata() { Dictionary dic = new Dictionary(); dic.Add("EntityCustomMetadataFieldId", "5bf81296-feda-6447-b45a-08d5cb91211c"); var filter = Builders.Filter.Eq("_id", "6c7bb4a5-d7cc-4a8d-aa92-b0c89ea0f7fe"); var update = Builders .Update.Push("CustomMetadata.Fields", dic); await _context.BsonAssets.FindOneAndUpdateAsync(filter, update); }