Insert element into nested array in Mongodb

前端 未结 3 1930
孤街浪徒
孤街浪徒 2021-01-04 09:39

I have this :

{
  \"_id\" : ObjectId(\"4fb4fd04b748611ca8da0d48\"),
  \"Name\" : \"Categories\",
  \"categories\" : [{
      \"_id\" : ObjectId(\"4fb4fd04b74         


        
3条回答
  •  滥情空心
    2021-01-04 10:15

    You can use the positional operator using Linq expressions too:

    public async Task Add(string productId, string categoryId, SubCategory newSubCategory)
    {
        var filter = Builders.Filter.And(
             Builders.Filter.Where(x => x.Id == productId), 
             Builders.Filter.ElemMatch(x => x.Categories, c => c.Id == categoryId));
        var update = Builders.Update.Push(x => x.Categories[-1].SubCategories, newSubCategory);
        await collection.FindOneAndUpdateAsync(filter, update);
    }
    

    And get yourself free of using hard-coded property names inside strings.

提交回复
热议问题