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

时间:2015-06-09 12:08:40

标签: c# mongodb insert driver mongodb-.net-driver

我有这个:

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

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

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

为我的案例添加一个示例。可以正常工作,但是在数组内输入时没有美元符号:

public async Task AddCustomMetadata()
       {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("EntityCustomMetadataFieldId", "5bf81296-feda-6447-b45a-08d5cb91211c");
            var filter = Builders<BsonDocument>.Filter.Eq("_id", "6c7bb4a5-d7cc-4a8d-aa92-b0c89ea0f7fe");
            var update = Builders<BsonDocument>.Update.Push("CustomMetadata.Fields", dic);
            await _context.BsonAssets.FindOneAndUpdateAsync(filter, update);
        }

答案 2 :(得分:0)

您也可以通过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);
}

让您摆脱在字符串中使用硬编码属性名的麻烦。