Search code examples
c#mongodbmongodb-.net-driver

How to call a stored JavaScript in MongoDb from C#


I'm evaluating the porting of SQL Server database to MongoDb.

The problem is moving stored procedures, I read about MongoDb stored JavaScript and I would like make some test in in .Net. I've installed MongoDb driver 2.4.0 and created this function on MongoDb named test_function:

function (x) 
{
  return x;
}

This is the code I use to try to invoke that function:

MongoClient oMongoClient = new MongoClient(Properties.Settings.Default.MongoCN);
IMongoDatabase oMongoDatabase = oMongoClient.GetDatabase("test_db");
var result = oMongoDatabase.RunCommand<BsonDocument>("test_function(3)");

I get this error:

An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll Additional information: JSON reader was expecting a value but found 'test_function'.


Solution

  • I think you can use this way to run a stored script:

    var cmd = new JsonCommand<BsonDocument>("{ eval: \"test_function(2)\" }");
    var result = db.RunCommand(cmd);
    

    But result is in BsonDocument to get the correct result you can use this methods:

    var intResult = result["retval"].ToInt32();