Create a gist now

Instantly share code, notes, and snippets.

Example of using the 10gen MongoDB CSharp driver in powershell.
# We assume that the driver is installed via the MSI.
[string] $mongoDriverPath;
# 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:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\MongoDB CSharpDriver 1.0").'(default)';
}
else {
$mongoDriverPath = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\MongoDB CSharpDriver 1.0").'(default)';
}
Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll";
# The [ordered] only works in PowerShell 3.0 an later.
[MongoDB.Bson.BsonDocument] $doc = [ordered]@{
"_id"= [MongoDB.Bson.ObjectId]::GenerateNewId();
"FirstName"= "Justin";
"LastName"= "Dearing";
"PhoneNumbers"= [MongoDB.Bson.BsonDocument] [ordered]@{
'Home'= '718-555-1212';
'Mobile'= '646-555-1212';
};
};
Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/powershell');
$collection = $db['example1'];
Write-Host "Insert";
$collection.Insert($doc);
$collection.FindOneById($doc['_id']);
$updates = @{'email'= 'justin@mongodb.org'};
$query = @{"_id"= $doc['_id']}
Write-Host "Update";
$collection.Update([MongoDB.Driver.QueryDocument]$query, [MongoDb.Driver.UpdateDocument]$updates);
$collection.FindOneById($doc['_id']);
Write-Host "Delete";
$collection.Remove([MongoDB.Driver.QueryDocument]$query);
$collection.FindOneById($doc['_id']);
@msneller

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

@djisdj
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