【问题标题】:How to call a stored JavaScript in MongoDb from C#如何从 C# 调用 MongoDb 中存储的 JavaScript
【发布时间】:2016-12-07 10:56:04
【问题描述】:

我正在评估将 SQL Server 数据库移植到 MongoDb。

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

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

我收到此错误:

MongoDB.Bson.dll 中出现“System.FormatException”类型的未处理异常 附加信息:JSON 阅读器期待一个值,但找到了“test_function”。

【问题讨论】:

    标签: c# mongodb mongodb-.net-driver


    【解决方案1】:

    这里有完全相同的问题: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

    有了这个 sn-p,你可以这样调用你的函数:

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

    【讨论】:

    • 谢谢,它仍然抛出异常:在 MongoDB.Driver.Core.dll 中发生类型为 'MongoDB.Driver.MongoCommandException' 的未处理异常附加信息:命令 test_function 失败:没有这样的 cmd:test_function。
    • 遇到了同样的异常。抱歉,我找到了另一种方法,请参阅答案更新。
    • eval 和 EvalAsync 已在 2.4.0 驱动程序中删除。我认为不可能从客户端调用存储的 js。也没有办法将 sql server 存储过程迁移到 Mongo。我的评估结束了,我意识到这是不可能的。
    【解决方案2】:

    我认为您可以使用这种方式来运行存储的脚本:

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

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

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

    【讨论】:

    • 当函数返回一个数字时它工作正常。现在我想尝试返回一个文档的列表。我将 test_function 更改为:function (x,y) { return db.MyDB.find({_id:1}); } 运行到 mongo shell 它返回一个文档。但从 dotnet 它不起作用。
    • @FDB AFAIK 您无法在 C# 中以这种方式获得数据库命令的结果,请为此提出另一个问题,我希望有人回答;)。
    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    相关资源
    最近更新 更多