Question

Hello I have a mongoDB Collection called Nodes whose structure is as follows:

{
  "_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"
}]
}

I created a new key called "mainentries" which is now storing the "studies" and "tests". So in order to support my new versions without hassle, I now want to write a method in my Setup Helper, which would enable me to read this collection - Check if studies,tests exists , If yes add the key "mainentries" and remove the studies/tests key.

My question is: What kind of query must I use to reach each collection of Nodes to check for the fields and update. I am using the MongoDB-CSharp community driver.

Would appreciate any help and pointers.

Was it helpful?

Solution

You can simply check whether the field(s) still exist(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);
}

If you don't want to migrate the data, but just remove the fields and create new ones, you can also do in a simple batch update using $exists, $set and $remove

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top