Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute mongodb shell script via C# driver

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

like image 780
Dao Avatar asked Aug 09 '11 21:08

Dao


1 Answers

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, ....}],
   ....

}
like image 63
Dao Avatar answered Sep 17 '22 17:09

Dao