Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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";
[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';
Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/powershell');
$collection = $db['example1'];
Write-Host "Insert";
$updates = @{'email'= ''};
$query = @{"_id"= $doc['_id']}
Write-Host "Update";
$collection.Update([MongoDB.Driver.QueryDocument]$query, [MongoDb.Driver.UpdateDocument]$updates);
Write-Host "Delete";

This comment has been minimized.

Copy link

commented Apr 16, 2015

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


This comment has been minimized.

Copy link

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
You can’t perform that action at this time.