Writing a boolean toggle query with the C# driver

Hi, I’m trying to replicate this mongo query using the C# driver:
.findOneAndUpdate({_id: id},[{$set:{present:{$eq:[false,"$present"]}}}]);

What would be the recommended way to write this query? So far the best solution I’ve come up with involves magic strings:

var pipeline = new EmptyPipelineDefinition<T>()
    .AppendStage("{$set:{Present:{$eq:[false,\"$Present\"]}}}", 
        BsonSerializer.LookupSerializer<T>());

collection.FindOneAndUpdateAsync(x => x.Id == id, Builders<T>.Update.Pipeline(pipeline));

Thanks!

I am using the following piece of code in order to toggle a field.
Although the field has to be an integer.

// the field type is ‘Expression<Func<TEntity, int>>’ in my case
var updateDef = Builders.Update.BitwiseXor(field, 1);
return await _collection.UpdateOneAsync(filter, updateDef, null, cancellationToken);

Hope this helps :slight_smile:

1 Like

Thanks for sharing a solution @Ivan_Povazan and welcome to the MongoDB Community!

1 Like