How to call a stored JavaScript in MongoDb from C#

前端 未结 2 1768
眼角桃花
眼角桃花 2021-01-20 06:27

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

相关标签:
2条回答
  • 2021-01-20 06:38

    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
    
    0 讨论(0)
  • 2021-01-20 06:54

    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();
    
    0 讨论(0)
提交回复
热议问题