0

Given the following:

{
    "_id" : 1,
    "name" : "Nature",
    "area": [
        {
            "place": "Some place",
            "discoveredBy": ""
        },
        {
            "place": "Some place 2",
            "discoveredBy": ""
        }
    ],
    "_id" : 2,
    "name" : "Tropics",
    "area": [
        {
            "place": "Some place",
            "discoveredBy": ""
        },
        {
            "place": "Some place 2",
            "discoveredBy": ""
        }
    ]
}

In code, I deleted the discoveredBy property. How do I now update (unset) my ENTIRE db using the C# driver so that discoveredBy is also deleted? The resulting db should look like:

{
    "_id" : 1,
    "name" : "Nature",
    "area": [
        {
            "place": "Some place"
        },
        {
            "place": "Some place 2"
        }
    ],
    "_id" : 2,
    "name" : "Tropics",
    "area": [
        {
            "place": "Some place"
        },
        {
            "place": "Some place 2"
        }
    ]
}

Currently when trying to perform a Find after my code change, it's failing because the discoveredBy property is no longer in code and the serialization processes can't find a place to store the removed property which still exists in the db. Hence the need to delete that field from the db in its entirety.

UPDATED WITH SOLUTION:

Thanks for all the input guys but this isn't a duplicate as everything I tried seemed to be deprecated when I tried running in C# with the new driver. Either way, here's the fix I eventually settled on. The key here is using "$[]" which according to MongoDB is new as of version 3.6. See https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[] for more information.

Here's the code:

{
   var filter = Builders<Scene>.Filter.Where(i => i.ID != null);
   var update = Builders<Scene>.Update.Unset("area.$[].discoveredBy");
   var result = collection.UpdateMany(filter, update, new UpdateOptions { IsUpsert = true});
}
C0d3 0n3
  • 97
  • 1
  • 10

1 Answers1

0

In your case do something like this:

db.collectionname.find({}).forEach(function(item) {
var ar = item.area;
for(var i = 0; i < ar.length; ++i) { 
    var x = ar[i];
    delete (x["discoveredBy"]);

}
db.collectionname.save(item);});
Parth Savadiya
  • 1,203
  • 3
  • 18
  • 40
  • 1
    Could this be an outdated example for C#? For instance, save seems to be deprecated for the newest driver and delete is no where to be found. – C0d3 0n3 Jun 05 '18 at 14:01