How to call a stored JavaScript in MongoDb from C#

非 Y 不嫁゛ 提交于 2019-12-02 00:48:48

问题


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'.


回答1:


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();



回答2:


The exact same question was here: MongoDB db.runCommand() from C#

My first answer was there, but I think, it's better to do here.

I think you could call with this code:

var doc = new BsonDocument(new Dictionary<string, string> { { "test_function", "3" }});
var command = new BsonDocumentCommand<int>(doc);
var result = db.RunCommand(command );

But, as you could see here, it is really not recommended to use stored procedures this way.

I have found another solution here:

https://gist.github.com/jamesikanos/b5897b1693b5c3dd1f87

With this snippet, you could call your function this way:

db.EvalAsync("test_function(2)").Result


来源:https://stackoverflow.com/questions/41015598/how-to-call-a-stored-javascript-in-mongodb-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!