Search code examples
c#mongodbmongodb-.net-driver

Calling a Stored Procedure in MongoDB via C#


I have a saved function in system.js called "addNumbers" which has 2 parameters:

function addNumbers( a , b ) {
    return a + b;
}

I wish to execute this function via C#, by adding 2 numbers which are inputted by a user. So far I have the following code:

MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase test = server.GetDatabase("test");

Console.WriteLine("Input two numbers: ");
string num1 = Console.ReadLine();
string num2 = Console.ReadLine();
BsonValue bv = test.Eval("addNumbers", num1, num2);
BsonValue bv1 = test.Eval(bv.AsBsonJavaScript.Code, num1, num2);

What I am doing wrong? As no sum is being displayed


Solution

  • So I just did a test locally. With

    db.system.js.save({
        _id : "myAddFunction" ,
        value : function (x, y){ return x + y; }
    });
    

    I got a saved function myAddFunction. With a little bit modification of your code:

    MongoClient client = new MongoClient("mongodb://192.168.122.1/test");
    MongoServer server = client.GetServer();
    MongoDatabase test = server.GetDatabase("test");
    
    Console.WriteLine("Input two numbers: ");
    string num1Str = Console.ReadLine();
    string num2Str = Console.ReadLine();
    int num1 = int.Parse(num1Str);
    int num2 = int.Parse(num2Str);
    
    BsonValue bv = test.Eval("myAddFunction");
    BsonValue bv1 = test.Eval(bv.AsBsonJavaScript.Code, num1, num2);
    Console.WriteLine(bv1);
    

    Now I get the right result displayed.