Skip to content

Instantly share code, notes, and snippets.

@leandromoh
Created January 23, 2024 15:09
Show Gist options
  • Save leandromoh/1e743749eea27858797169733e87a57f to your computer and use it in GitHub Desktop.
Save leandromoh/1e743749eea27858797169733e87a57f to your computer and use it in GitHub Desktop.
public class PipelineStageDefinitionBuilderSet<TDocument>
{
private UpdateDefinition<TDocument> current;
public PipelineStageDefinitionBuilderSet()
{
current = new BsonDocument();
}
public IPipelineStageDefinition ToPipelineStageDefinition()
{
var y = BsonDocument.Parse(
"""
{ $set : "FOO" }
""");
y["$set"] = current.RenderToBsonDocument();
var pipe = new BsonDocumentPipelineStageDefinition<TDocument, TDocument>(y);
return pipe;
}
public PipelineStageDefinitionBuilderSet<TDocument> Set<TField>(Expression<Func<TDocument, TField>> field, TField value)
{
var xs = Builders<TDocument>.Update.Set(field, value);
var y = xs.RenderToBsonDocument();
var temp = y["$set"].AsBsonDocument;
current = Builders<TDocument>.Update.Combine(current, temp).RenderToBsonDocument();
return this;
}
public PipelineStageDefinitionBuilderSet<TDocument> Push<TField>(Expression<Func<TDocument, IEnumerable<TField>>> field, TField value)
{
var xs = Builders<TDocument>.Update.Push(field, value);
var y = xs.RenderToBsonDocument();
var temp = y["$push"].AsBsonDocument.ElementAt(0);
var d = BsonDocument.Parse(
$$"""
{
"{{temp.Name}}": { $concatArrays: [ "${{temp.Name}}", [ "FOO" ] ] }
}
""");
d[temp.Name]["$concatArrays"][1][0] = temp.Value;
current = Builders<TDocument>.Update.Combine(current, d).RenderToBsonDocument();
return this;
}
public PipelineStageDefinitionBuilderSet<TDocument> Inc<TField>(Expression<Func<TDocument, TField>> field, TField value)
{
var xs = Builders<TDocument>.Update.Inc(field, value);
var y = xs.RenderToBsonDocument();
var temp = y["$inc"].AsBsonDocument.ElementAt(0);
var d = BsonDocument.Parse(
$$"""
{
"{{temp.Name}}": { $sum: [ "${{temp.Name}}", "FOO" ] }
}
""");
d[temp.Name]["$sum"][1] = temp.Value;
current = Builders<TDocument>.Update.Combine(current, d).RenderToBsonDocument();
return this;
}
}
@leandromoh
Copy link
Author

// https://stackoverflow.com/a/32146281
public static BsonDocument RenderToBsonDocument<T>(this FilterDefinition<T> filter)
{
    var serializerRegistry = BsonSerializer.SerializerRegistry;
    var documentSerializer = serializerRegistry.GetSerializer<T>();
    return filter.Render(documentSerializer, serializerRegistry);
}

public static BsonDocument RenderToBsonDocument<T>(this UpdateDefinition<T> filter)
{
    var serializerRegistry = BsonSerializer.SerializerRegistry;
    var documentSerializer = serializerRegistry.GetSerializer<T>();
    return filter.Render(documentSerializer, serializerRegistry).AsBsonDocument;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment