Monday, February 20, 2012

PowerShell and MongoDB

I was exploring MongoDB last weekend and was a bit skeptical at first. The relational model (I used to teach it) is so ingrained into my way of thinking. Like the florescent bulbs in my garage during the Winter, the light slowly started to brighten. I can now see a lot of uses for a schema free database (especially as a tool for prototyping). After playing around with the JavaScript interface, I decided to see what PowerShell could do with it.

Luckily, there is a driver available for download.

Assuming you have MongoDB, the C# driver and PowerShell installed, you can play around with the following code:
# Add a reference to our dll        
Add-Type -Path 'C:\Program Files (x86)\MongoDB\CSharpDriver 1.3.1\MongoDB.Driver.dll'

# Name our test db (not actually created until we insert)
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/PowerShellMongoTest');

# Name or test collection
$coll = $database["Stuff"]

# Define a couple list
$languages = @("C#","Haskell","PowerShell","Python")
$beers = @("Honkers Ale","Stella","Summer Shandy","Yuengling")

# Define our document
$doc = @{FirstName="Wes"; LastName="Stahler"; Languages=$languages; Beers=$beers}
$collection.Insert($doc)
$info = $collection.FindAll()
$info | Format-Table -AutoSize

#$collection.RemoveAll()

This yields:
Name       Value
---- -----
_id 4f42b6798359da1e7ce51bfb
Beers {Honkers Ale, Stella, Summer Shandy, Yuengling}
LastName Stahler
Languages {C#, Haskell, PowerShell, Python}
FirstName Wes

I will be experimenting more with MongoDB.
Share your insights with me if you decide to explore it as well.

Enjoy!

4 comments:

John J. Kavanagh said...

Mmmmmmm Yuengling

Unknown said...

Indeed....

beefarino said...

You may want to look at the MongoDB PowerShell provider available at http://mosh.codeplex.com.

Unknown said...

I will! Thanks for sharing Jim!