2014-03-24 54 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