2014-03-24 94 views
0

你好,我有一個MongoDB的集合稱爲節點,其結構如下:的MongoDB/C#更新集合項

{ 
    "_id" : new BinData(3, "Ljot2wCBskWG9VobsLA0zQ=="), 
    "logicalname" : "Test Node", 
    "host" : "eh5tmb054pc", 
    "port" : 104, 
    "appendtimestamp" : false, 
    "studies" : ["1.3.12.2.1107"], 
    "tests" : [], 
    "mainentries" : [{ 
    "_id" : "1.3.12.2.1107", 
    "Index" : 0, 
    "Type" : "Study" 
}] 
} 

我創建了一個名爲「mainentries」這是目前存儲「研究」和「測試新的密鑰」。因此,爲了支持我的新版本而沒有麻煩,我現在想在我的設置助手中編寫一個方法,這將使我能夠閱讀這個集合 - 檢查研究,測試是否存在,如果是,請添加關鍵字「mainentries」並刪除研究/測試的關鍵。

我的問題是:我必須使用什麼樣的查詢才能到達每個節點集合以檢查字段並進行更新。我正在使用MongoDB-CSharp社區驅動程序。

希望得到任何幫助和指點。

回答

0

你可以簡單地檢查現場(S)是否仍然存在(S):

var collection = db.GetCollection<Node>("nodes"); 
var nodes = collection.Find(Query.And(// might want Query.Or instead? 
       Query<Node>.Exists(p => p.Tests), 
       Query<Node>.Exists(p => p.Studies)).SetSnapshot(); 

foreach(var node in nodes) { 
    // maybe you want to move the Tests and Studies to MainEntries here? 
    node.MainEntries = new List<MainEntries>(); 
    node.Test = null; 
    node.Studies = null; 
    collection.Update(node); 
} 

如果您不想遷移數據,而只是刪除領域,創造新的,你可以也做一個簡單的批量更新使用$exists,$set$remove

+0

感謝您的答覆。我想遷移數據。我無法使用查詢 .Exists - 因爲它無法將非泛型類型與類型參數一起使用。 – Goks

+0

咦?不知道我明白。無論如何,你可以使用Query.Exists(「studies」)嗎? – mnemosyn

+1

是的。 Query.Exists(「研究」)正在工作。非常感謝。 – Goks