将元素插入Mongodb中的嵌套数组中

Uok*_*imi 8 c# insert driver mongodb mongodb-.net-driver

我有这个 :

{
  "_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
  "Name" : "Categories",
  "categories" : [{
      "_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
      "name" : "SubCategory",
      "sub-categories" : [{
          "_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
          "name" : "SubSubCategory",
          "standards" : []
        }]
    }]
}
Run Code Online (Sandbox Code Playgroud)

我想使用C#驱动程序添加一个新的SubCategory.有最佳方​​法吗?

rno*_*nko 17

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • 好的!但是如果数组还不存在呢?有没有办法在这里创建它然后推送? (4认同)

lmc*_*iro 5

您也可以使用 Linq 表达式使用位置运算符:

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.ElemMatch(x => x.Categories, c => c.Id == categoryId));
    var update = Builders<Product>.Update.Push(x => x.Categories[-1].SubCategories, newSubCategory);
    await collection.FindOneAndUpdateAsync(filter, update);
}
Run Code Online (Sandbox Code Playgroud)

让自己摆脱在字符串中使用硬编码的属性名称。