Skip to content

Instantly share code, notes, and snippets.

@zippy1981
Created March 4, 2011 16:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zippy1981/854911 to your computer and use it in GitHub Desktop.
Save zippy1981/854911 to your computer and use it in GitHub Desktop.
Example of using the 10gen MongoDB CSharp driver in powershell.
# We assume that the driver is installed via the MSI.
[string] $mongoDriverPath = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\MongoDB CSharpDriver 0.11").'(default)';
[string] $connectionString = 'mongodb://localhost/atlantisSchemaEngine';
Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll";
Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";
try {
[MongoDB.Driver.MongoDatabase] $db = [MongoDB.Driver.MongoDatabase]::Create($connectionString);
[MongoDB.Bson.BsonDocument] $doc # = New-Object -TypeName MongoDB.Bson.BsonDocument;
$doc["_id"] = [MongoDB.Bson.ObjectId]::GenerateNewId();
$doc["FirstName"] = "Justin";
$doc["LastName"] = "Dearing";
$doc["PhoneNumbers"] = New-Object -TypeName MongoDB.Bson.BsonDocument;
$doc["PhoneNumbers"].Add('Home', '718-641-2098');
$doc["PhoneNumbers"].Add('Mobile', '646-288-5621');
# Download Invoke-GenericMethod.ps1 from http://pastebin.com/dRqZd0AA modified version of script available here http://www.leeholmes.com/blog/2007/06/19/invoking-generic-methods-on-non-generic-classes-in-powershell/
Invoke-GenericMethod $db["test"] Insert MongoDB.Bson.BsonDocument $doc;
} catch [Exception] {
$_.Exception.ToString();
}
@msneller
Copy link

Thanks for posting this. How would you query with multiple values, like by First name and Home phone number?

@djisdj
Copy link

djisdj commented Apr 27, 2015

This example no longer works, I have tested it on Powershell x86 and x64 bit, with the installation of # drive drive 1.9 last one with msi installed. In that case it does not find any registry settings.

With just trying to reference the same to the local dll files I get the message that it's dependencies are missing. for both the dlls. I have tested the same on Powershell 3.0 and 4.0 x32 and x64 bit. With driver versions 1.9, 1.10 and 2.0. Any suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment