Just A Programmer We're just programmers


Using MongoDB in Powershell

Readers of this blog know that I’ve been using MongoDB for a while, and I’ve recently become very excited about Powershell. Well recently I’ve been able to combine the two together for pure dynamically typed, schema-less, non-relational awesomeness. Such awesomeness is begging to be shared.

To get started you will need version 1.1 of the official 10gen CSharp driver for Mongodb. At the time of this writing 1.1 has not been released, so your going to have to pull the latest version from github and compile it yourself. The minimal revision of the trunk you will need is this one. First download and install the MSI (or download the source, build the MSI and install it). Then open up your favorite text editor or Powershell IDE. Personally I am a fan of Powershell ISE or plain old vim, with some configuration modifications. Now we will load the bson and driver DLLs via the Add-Type cmdlet.

# Check to see if we are running the 64 bit version of Powershell.
# See http://stackoverflow.com/questions/2897569/visual-studio-deployment-project-error-when-writing-to-registry
if ([intptr]::size -eq 8) {
    $mongoDriverPath = (Get-ItemProperty "HKLM:SOFTWAREWow6432NodeMicrosoft.NETFrameworkv3.5AssemblyFoldersExMongoDB CSharpDriver 1.0").'(default)';
else {
    $mongoDriverPath = (Get-ItemProperty "HKLM:SOFTWAREMicrosoft.NETFrameworkv3.5AssemblyFoldersExMongoDB CSharpDriver 1.0").'(default)';
Add-Type -Path "$($mongoDriverPath)MongoDB.Bson.dll";
Add-Type -Path "$($mongoDriverPath)MongoDB.Driver.dll";

Since the Csharp Driver MSI is 32 bits, it creates the registry entries in the Wow6432Node. Therefore, we have to check to see if we are running in the 32 or 64 bit version of Powershell . Credit to an anonymous commenter on the msgoodies blog for providing this size of a pointer trick to determine if you are running a 32 or 64 bit system.

The next thing we want to do is to create a BSON document. This is surprisingly easy.

[MongoDB.Bson.BsonDocument] $doc = @{
    "_id"= [MongoDB.Bson.ObjectId]::GenerateNewId();
    "FirstName"= "Justin";
    "LastName"= "Dearing";
    "PhoneNumbers"= [MongoDB.Bson.BsonDocument] @{
        'Home'= '718-555-1212';
        'Mobile'= '646-555-1212';

As you can see Powershell can convert a HashTable to a BsonDocument. This is because of the public constructor BsonDocument(IDictionary hashTable). Powershell can use these one parameter constructors to cast an object. You can use the same Hashtable trick for the QueryDocument and UpdateDocument classes.

Now that we have our BsonDocument, its time to perform basic crud operations.

$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/powershell');
$collection = $db['example1'];
Write-Host "Insert";
$updates = @{'$set' = @{'email'= 'justin@mongodb.org'}};
$query = @{"_id"= $doc['_id']}
Write-Host "Update";
$collection.Update([MongoDB.Driver.QueryDocument]$query, [MongoDb.Driver.UpdateDocument]$updates);
Write-Host "Delete";

This gives us the output below.

_id                                                         4dc5e5a43b42bd41d0154679
LastName                                                    Dearing
PhoneNumbers                                                {Mobile=646-555-1212, Home=718-555-1212}
FirstName                                                   Justin

PS E:srcgistgist-854911> powershell.exe -file .MongoTest.ps1


Name                                                        Value
----                                                        -----
_id                                                         4dc636c33b42bd3d7c8dc3a4
LastName                                                    Dearing
PhoneNumbers                                                {Mobile=646-555-1212, Home=718-555-1212}
FirstName                                                   Justin
FirstName                                                   Justin
LastName                                                    Dearing
PhoneNumbers                                                {Mobile=646-555-1212, Home=718-555-1212}
_id                                                         4dc636c33b42bd3d7c8dc3a4
email                                                       justin@mongodb.org

As you can see, its not very hard to use the 10Gen MongoDB Csharp driver from within Powershell. Using Powershell with the MongoDb C-Sharp driver has many possibilities. First of all, adhoc mongodb queries from inside of powershell. Secondly,  The code for this example is available in its entirety here.

  • Pingback: Justin Dearing

  • Pingback: JeffTruman

  • Pingback: Robert Groves

  • Pingback: Tome Tanasovski

  • Pingback: Jim Poshible

  • Pingback: Michael Kennedy

  • Pingback: Jidé - Mr Friouaire

  • Anonymous

    I get this error:

    PS C:UsersMatt> $collection.Insert($doc);Cannot find an overload for “Insert” and the argument count: “1″.At line:1 char:19+ $collection.Insert <<< ($collection | gm | ? { $_.Name -eq “Insert” } ).definition

    MongoDB.Driver.SafeModeResult Insert[TDocument](TDocument document), MongoDB.Driver.SafeModeResult Insert[TDocument](TDocument document, MongoDB.Driver.SafeMode safeMode)
    this is $doc:
    PS C:UsersMatt> $docName                                                        Value—-                                                        —–_id                                                         4de1fb3d4985a212a8be2dd1LastName                                                    DearingPhoneNumbers                                                {Mobile=646-555-1212, Home=718-555-1212}FirstName                                                   JustinPS C:UsersMatt> $doc.GetType()IsPublic IsSerial Name                                     BaseType——– ——– —-                                     ——–True     True     BsonDocument                             MongoDB.Bson.BsonValue

    • Anonymous

      Like I stated at the beginning of the article, version 1.1 of the driver has not been released. You will have to compile the driver and MSI yourself to get that code to work now., If you can’t build the setup project because you only have Visual Studio Express or SharpDevelop, you can change the top of the script to load the dll from a static path.

  • Anonymous

    Sorry dude I clicked the link and didn’t look back.. :@amonkeysden:disqus 

    good news I can still try it out myself  :)

  • http://www.k9stud.com Puppies

     Thanks for sharing the process of Using MongoDB in Powershell.i was looking for it since a long time.

  • Pingback: Justin Dearing

  • Pingback: Working with MongoDB and PowerShell | Kristof Kowalski