drishit96
drishit96

Reputation: 337

Unset multiple properties using C# mongodb driver

I have this mongo query that I want to run using the C# MongoDB driver:

db.test.update(
   { rate: "unknown" },
   { $unset: { qt: "", cost: "", res: "", ... } }
)

Upvotes: 2

Views: 1688

Answers (1)

drishit96
drishit96

Reputation: 337

The documentation didn't cover this case, but I'm glad the tests are good enough, though it takes some time to dig into them. Here's the test where I came to know one can chain multiple Unset methods: TestUnsetTwice

Here's my final solution: Provided a list of properties to update, loop through each property and call the Unset method on UpdateDefinition.

FilterDefinition<TDocument> filterDefinition = Builders<TDocument>.Filter.Eq("rate", "unknown");
UpdateDefinition<TDocument> updateDefinition = null;
UpdateDefinitionBuilder<TDocument> updateDefinitionBuilder = Builders<TDocument>.Update;

foreach (String o in propertiesToDelete)
{
     if(updateDefinition == null)
        updateDefinition = updateDefinitionBuilder.Unset(o);
     else
        updateDefinition = updateDefinition.Unset(o);
}

var collection = GetCollection<TDocument>();
var updateRes = collection.UpdateOne(filterDefinition, updateDefinition);

Upvotes: 3

Related Questions