如何从C#调用MongoDb中存储的JavaScript
我正在评估将SQL Server数据库移植到MongoDb。
问题是移动存储过程,我读了MongoDb存储的JavaScript,我想在.Net中进行一些测试。 我已经安装了MongoDb驱动程序2.4.0并在名为test_function
上创建了这个函数:
function (x) { return x; }
这是我用来尝试调用该函数的代码:
MongoClient oMongoClient = new MongoClient(Properties.Settings.Default.MongoCN); IMongoDatabase oMongoDatabase = oMongoClient.GetDatabase("test_db"); var result = oMongoDatabase.RunCommand("test_function(3)");
我收到此错误:
MongoDB.Bson.dll中出现未处理的“System.FormatException”类型exception。附加信息:JSON reader期望一个值,但找到了’test_function’。
我想你可以用这种方式运行一个存储的脚本:
var cmd = new JsonCommand("{ eval: \"test_function(2)\" }"); var result = db.RunCommand(cmd);
但结果是在BsonDocument
中获取正确的结果,您可以使用此方法:
var intResult = result["retval"].ToInt32();
完全相同的问题在这里: 来自C#的MongoDB db.runCommand()
我的第一个答案就在那里,但我认为,最好在这里做。
我想你可以使用这段代码调用:
var doc = new BsonDocument(new Dictionary { { "test_function", "3" }}); var command = new BsonDocumentCommand(doc); var result = db.RunCommand(command );
但是,正如您在此处看到的,实际上不建议以这种方式使用存储过程。
我在这里找到了另一个解决方案
https://gist.github.com/jamesikanos/b5897b1693b5c3dd1f87
使用此代码段,您可以通过以下方式调用函数:
db.EvalAsync("test_function(2)").Result