how to call stored javascript from dotnet and read results

461 views
Skip to first unread message

Fabrizio Landi

unread,
Dec 20, 2016, 3:46:08 PM12/20/16
to mongodb-user
hi, i create this function on mongo server

function (x)
{
    return db.MyDB.find({_id:1});
 }

running this code in mongo it returns 1 document

db.loadServerScripts();

test_function(2);

what i need is to call that function from dotnet.

this the code:

            MongoClient oMongoClient = new MongoClient(Properties.Settings.Default.MongoCN);
            IMongoDatabase oMongoDatabase = oMongoClient.GetDatabase(Properties.Settings.Default.MongoDB);

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

this into result:

{{ "retval" : { "_mongo" : { "slaveOk" : false, "host" : "EMBEDDED" }, "_db" : { "_mongo" : { "slaveOk" : false, "host" : "EMBEDDED" }, "_name" : "Fuoco" }, "_collection" : { "_mongo" : { "slaveOk" : false, "host" : "EMBEDDED" }, "_db" : { "_mongo" : { "slaveOk" : false, "host" : "EMBEDDED" }, "_name" : "Fuoco" }, "_shortName" : "DocCache", "_fullName" : "Fuoco.DocCache" }, "_ns" : "Fuoco.DocCache", "_query" : { "_id" : 1.0 }, "_fields" : null, "_limit" : 0.0, "_skip" : 0.0, "_batchSize" : 0.0, "_options" : 0.0, "_cursor" : null, "_numReturned" : 0.0, "_special" : false }, "ok" : 1.0 }}

what's wrong?


Wan Bachtiar

unread,
Jan 4, 2017, 10:03:53 PM1/4/17
to mongodb-user

what’s wrong?

Hi Fabrizio,

The result that you are seeing is the string representation of the cursor returned from your find(). i.e. db.MyDB.find({_id:1}). Eval only returns the cursor, it doesn’t iterate for you. You can try swapping the function content to db.MyDB.findOne({_id:1}) , db.stats() or anything that returns a non-cursor result.

Having said the above, eval command has been deprecated since version 3.0. Also there are performance and concurrency limitations to running JavaScript script inside MongoDB server. Depending on your use case, separating application logic in two places (application code and database) may complicate the logic flow as well.

I would highly recommend to reconsider your stored JavaScript procedure strategy. Utilise the interface provided via MongoDB .Net/C# driver instead, see Query the Collection Tutorial for example to run find().

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages