使用MongoDb和C#更新嵌入式字段

时间:2016-10-11 10:31:06

标签: c# mongodb

我有这个文件

    { "_id" : ObjectId("57f65ed25ced690b5408a9d1"), "fbId" : "7854", "Name" : "user1", "pass" : "user1", "Watchtbl" : [ { "wid" : "745", "name" : "azs", "Symboles" : [ { "Name" : "nbv" } ] }, { "wid" : "8965", "name" : "bought stock1", "Symboles" : [ { "Name" : "AAA" }, { "Name" : "BSI" }, { "Name" : "EXXI" }, { "Name" : "AMD" } ] }, { "wid" : "9632", "name" : "bought stock3", "Symboles" : [ { "Name" : "AAA" }, { "Name" : "AMD" } ] } ] }

我尝试通过_id和Watchtbl.wid进行搜索并更新Watchtbl.name和Watchtbl.Symboles,所以我尝试从名称开始,这是我的代码:

    var collectionWatchtbl = _database.GetCollection<BsonDocument>("UsersWatchtbls");
    var filter = Builders<BsonDocument>.Filter.Eq("_id", id) & Builders<BsonDocument>.Filter.Eq("Watchtbl.wid", wid );
    var update = Builders<BsonDocument>.Update.Set("Watchtbl.name", NameComboBox.SelectedItem.ToString());
    var result = await collectionWatchtbl.UpdateOneAsync(filter, update);

但没有任何事情发生,即使没有错误。 而且如果我尝试更新Watchtbl.Symboles,我必须两次执行相同的代码,没有其他方法可以同时更新所有代码。

有1项要更新的解决方案

BsonArray arrSym = new BsonArray();
            foreach (var item in SymbolesListBox.SelectedItems)
            {
                arrSym.Add(new BsonDocument("Name", item.ToString()));
            }

            var filter = Builders<UserWatchTblCls>.Filter.Where(x=> x.Id == ObjectId.Parse(id) && x.WatchTbls.Any(i=> i.WID == wid) );
            var update = Builders<UserWatchTblCls>.Update.Set(x=> x.WatchTbls[-1].Name, NameComboBox.SelectedItem.ToString()).Set(x => x.WatchTbls[-1].Symbols, arrSym);
            await collectionWatchtbl.UpdateManyAsync(filter, update);

如果我删除此部分,将工作并更新名称

.Set(x => x.WatchTbls[-1].Symbols, arrSym)

但我需要更新Symboles,我收到此错误

  

严重级代码描述项目文件行抑制状态   错误CS1660无法将lambda表达式转换为类型&#39; FieldDefinition&#39;因为它不是委托类型FinalWatchTbl C:\ Users \ amin- \ Desktop \ FinalWatchTbl \ FinalWatchTbl \ UpdateFrm.cs 117 Active

解决方案 如果我需要将bson数组更新为嵌套文档,则可以使用

  

&#34; Watchtbl $ Symboles&#34;   所以解决方案是:

BsonArray arrSym = new BsonArray();

            var filter = Builders<UserWatchTblCls>.Filter.Where(x => x.Id == ObjectId.Parse(id) && x.WatchTbls.Any(i => i.WID == wid));
            var update = Builders<UserWatchTblCls>.Update.Set(x => x.WatchTbls[-1].Name, NameComboBox.SelectedItem.ToString()).Set("Watchtbl.$.Symboles", arrSym);
            //var update = Builders<UserWatchTblCls>.Update.Set("Watchtbl.$.Symboles", arrSym);
            await collectionWatchtbl.UpdateManyAsync(filter, update);

1 个答案:

答案 0 :(得分:2)

查找如何update documents in an array using the positional operator

array_reduce($array1, function ($s, $k) { return $s[$k] ?? false; }, $array2)