如何从C#调用MongoDb中存储的JavaScript [英] How to call a stored JavaScript in MongoDb from C#
问题描述
我正在评估SQL Server数据库到MongoDb的移植.
I'm evaluating the porting of SQL Server database to MongoDb.
问题在于移动存储过程,我读到有关MongoDb存储的JavaScript的信息,我想在.Net中进行一些测试.我已经安装了MongoDb驱动程序2.4.0,并在名为test_function
的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)");
我收到此错误:
MongoDB.Bson.dll中发生了'System.FormatException'类型的未处理异常 附加信息:JSON阅读器原本需要一个值,但找到了'test_function'.
An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll Additional information: JSON reader was expecting a value but found 'test_function'.
推荐答案
我认为您可以使用这种方式来运行存储的脚本:
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);
但是结果在BsonDocument
中,以获得正确的结果,您可以使用以下方法:
But result is in BsonDocument
to get the correct result you can use this methods:
var intResult = result["retval"].ToInt32();
这篇关于如何从C#调用MongoDb中存储的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!