Dynamically Export Pipeline to Specific Language in MongoDb

Viewed 22

As you know it is possible to export a MongoDb pipeline to a specific language manually (read this). But I wonder if it is possible to consume this functionality programmatically using c# and .Net core. If there is a library for this that would be the best .

1 Answers

MongoDB Compass uses a package to transpile an input to output in various languages. See this project for the source code. There is a npm package that you can include. AFAIK there is no way to include the npm package in C# directly, so you'd have to use this in a compatible environment, e.g. on a web page or build a Node application/API that publishes the functionality.

A simpler way would be to render the pipeline to a string; most MongoDB drivers should be capable of parsing BSON and running the pipeline. In a simple example, the following code

var pipeline = new EmptyPipelineDefinition<User>()
    .Match(u => u.Name.Contains("abc"))
    .Sort(Builders<User>.Sort.Ascending(x => x.Name))
    .Limit(100);
var reg = BsonSerializer.SerializerRegistry;
var ser = reg.GetSerializer<User>();
var rendered = pipeline.Render(ser, reg);
var pipelineStr = "[" + string.Join(", " + Environment.NewLine, rendered.Documents) + "]";

creates this output

[{ "$match" : { "Name" : /abc/s } }, 
{ "$sort" : { "Name" : 1 } }, 
{ "$limit" : 100 }]
Related