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});
}
2
  • 1
    If you found a solution not given in the duplicate you should add it there. Commented Jun 5, 2018 at 23:55
  • @DourHighArch done Commented Jun 6, 2018 at 0:28

1 Answer 1

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);});
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.