如何从 C# 中调用存储在 MongoDb 中的 JavaScript

How to call a stored JavaScript in MongoDb from C#

我正在评估将 SQL 服务器数据库移植到 MongoDb。

问题是移动存储过程,我阅读了有关 MongoDb 存储 JavaScript 的信息,我想在 .Net 中进行一些测试。我已经安装了 MongoDb 驱动程序 2.4.0 并在 MongoDb 上创建了名为 test_function:

的函数
function (x) 
{
  return x;
}

这是我用来尝试调用该函数的代码:

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

我收到这个错误:

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

完全相同的问题在这里:MongoDB db.runCommand() from C#

我的第一个答案在那里,但我认为,最好在这里做。

我想你可以用这个代码调用:

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

但是,如您所见here,确实不建议以这种方式使用存储过程。

我在这里找到了另一个解决方案:

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

使用此代码段,您可以这样调用您的函数:

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

我想你可以用这种方式来运行一个存储的脚本:

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

但结果在 BsonDocument 中,要获得正确的结果,您可以使用以下方法:

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