12

I have read this question and haven't understand. Is there ability to execute arbitrary mongodb shell script via C# driver?

3 Answers 3

19
var mongoServer = MongoServer.Create("mongodb://<connectionstring>"); 
var database = mongoServer.GetDatabase("mydatabase"); 
string mycollectionCount database.Eval("function() { return db.mycollection.count(); }").ToString();

This is useful when you are trying to change property types for example like this:

string updateScript = @"
function () { 
    db.some_items.find().forEach(function(documentItem) {
        documentItem.some_collection.forEach(function(collectionItem) {
            if (typeof collectionItem.SomeProperty === 'number' 
                && Math.floor(collectionItem.someProperty) === collectionItem.someProperty)
            {
                collectionItem.someProperty = '' + collectionItem.someProperty;
            }
        });
        db.modules_elementary.save(documentItem);
    });

    return true;
}";
var updateResult = MongoReadDatabase.Database.Eval(updateScript).ToString();
if (updateResult != "true")
{
    throw new ApplicationException("Update of something failed");
}

This code changes type of someProperty which is element of a collection of a collection:

some_items mongo collection:

{
   some_collection: [{ someProperty: 12, ....}],
   ....

}
Sign up to request clarification or add additional context in comments.

3 Comments

May I please know if there is a way for the invoked javascript to return complex types ( which would ultimately be POCOs in the C# code ) back to the C# module?
@CSLewis If I'm not mistaken mongodb .net driver for Database.Eval() method returns BsonValue - the result of script execution on server. You can try to cast it to some BsonDocument, taking into consideration, that script execution could be failed by server and instead some Data in BsonValue you will have error message in the Eval()'s result. Anyways, this all code is a hack. If you are using this code in a normal app execution flow, you are definitely doing something wrong.
Thx. Could you please take a quick glance at stackoverflow.com/questions/35456071/… ?
4

No, you'd need launch a Mongo shell process, using something like Process.Start, and pass in the command you want to execute, e.g.

mongo.exe mydb --eval "printjson(db.getCollectionNames())"

However, the C# driver can do most things the shell can, so if possible it's much easier to use the driver directly.

3 Comments

I haven't tested you proposal to run mongo admin util using Process.Start and passing it command to execute. But it seems that it should work. It's a pity, that I cannot manage only with C# driver here. Using mongo admint util and Process.Start looks a bit clumsy. If nobody adds any new idea how to use only C# driver to run arbitrary mongo shell script in nearest time, I will accept this answer.
Caution: even though it is a working solution, it is very wrong in terms of security, portability and robustness.
Are you saying that it isn't possible to execute arbitrary queries for update/retrieval at all? I'm very much in favor of C#, lambda expressions etc. but when it come to MongoDb, a lot of help comes in form of script (also trying out different things in a client produces script too). When I convert that to C#'ish code, I end up with a gazillion of new BsonDocument(...) nested into each other beyond the point of decency and sanity.
3

I have not tried it but I think this is what you are looking for:

MongoServer.RunAdminCommand Method (String) http://api.mongodb.org/csharp/1.1/html/a83249ae-0989-7c24-7240-4506053d83c1.htm

3 Comments

server.RunAdminCommand(@"db.blog.insert({title: ""My Blog Post""});"); gives error Command 'db.blog.insert({title: "My Blog Post"});' failed: no such cmd: db.blog.insert({title: "My Blog Post"}); (response: { "errmsg" : "no such cmd: db.blog.insert({title: \"My Blog Post\"});", "bad cmd" : { "db.blog.insert({title: \"My Blog Post\"});" : true }, "ok" : 0 })
Seems that arbitrary script couldn't be executed using MongoServer.RunAdminCommand() method.
@Dao + by the MogoDB User => can lead to permission escalation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.