2017-04-03 31 views
0

如果我有一個包含數組的數組的文檔,如何更新第二個數組的字段?mongodb c#在數組中設置數組值

例如,使用MongoDB的C#的驅動程序,我想更新的領域IWantToUpdateThis其中值是約翰·史密斯:

{ 
    { 
     "_id" : 0, 
     "Guff" : "Blah", 
     "FirstArray" : [ 
      { 
       "Blah" : "Guff", 
       "SecondArray" : [ 
        { 
         "IWantToUpdateThis" : "John Smith", 
         "ButNotThis" : "Not me" 
        }, 
        { 
         "IWantToUpdateThis" : "Will Smith", 
         "ButNotThis" : "Not me" 
        } 
       ] 
      } 
     ] 
    } } 

我嘗試了各種選項,例如:

var filter = Builders<BsonDocument>.Filter.Eq("FirstArray.SecondArray.IWantToUpdateThis", "John Smith"); 
var update = Builders<BsonDocument>.Update.Set("FirstArray.SecondArray.$.IWantToUpdateThis", "My New Value"); 
var result = collection.UpdateOne(filter, update); 

但我似乎無法更新價值。

編輯補充: 當問題被提出使用MongoDB的版本是v3.2.12-69-g45cc6d2

回答

0

我已經想通了一些作品,但我不能相信這是最好的解決辦法的問題:

var collection = _database.GetCollection<Model>("Stuff"); 
var filter = Builders<Model>.Filter.Eq("FirstArray.SecondArray.IWantToUpdateThis", OldValue); 
var docIds = collection.Find(filter).Project(x => x.Id).ToList(); 
foreach (var docId in docIds) 
{ 
    var model = collection.Find(e => e.Id == docId).FirstOrDefault(); 
    foreach (var first in model.FirstArray) 
    { 
     foreach(var second in first.SecondArray) 
     { 
      if (second.IWantToUpdateThis == OldValue) 
       second.IWantToUpdateThis = NewValue; 
     } 
    } 
    collection.ReplaceOne(r => r.Id == docId, model); 
} 

如果有人想出了另一種答案,那很可能是比我更好的方法,我在這裏離開這個答案只顯示一種可能的前進道路應別人發現自己與我相同的死衚衕。