Question:
I already tried with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$mongoDbDriverPath = ' C:\Mongodb\net45\' $mongoServer = 'localhost:27017' Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll" Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll" $databaseName = "test" $collectionName = "sample" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) Write-Host $server,$database,$collection $query = [MongoDB.Driver.Builders.Query]::EQ("Name", "sample") $results = $collection.Find($query) $results |
but it shows some errors:
New-Object : Exception calling “.ctor” with “1” argument(s): “Could not load file or assembly ‘System.Runtime.InteropServices.RuntimeInformation,Version=4.0.0.0,`Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The system cannot find the file specified.”
At D:\Users\xxxxxx\Desktop\Mongodb With Powershell\task1.ps1:8 char:11
How do I overcome this error?
Answer:
I know I am little late but I have been playing around with Mongodb and Powershell for the last couple days. The easiest solution that I have found is to install the MongoDB cmdlets from the Powershell gallary:
https://github.com/nightroman/Mdbc
Step 1: Get and install.
Mdbc is distributed as the PowerShell Gallery module Mdbc. In
PowerShell 5.0 or with PowerShellGet you can install it by this
command:
1 2 |
Install-Module Mdbc |
Step 2: In a PowerShell command prompt import the module:
1 2 |
Import-Module Mdbc |
Step 3: Take a look at help:
1 2 3 |
help about_Mdbc help Connect-Mdbc -full |
Then go through the following steps to see if the setup is working:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Load the module Import-Module Mdbc # Connect the new collection test.test Connect-Mdbc . test test -NewCollection # Add some test data @{_id=1; value=42}, @{_id=2; value=3.14} | Add-MdbcData # Get all data as custom objects and show them in a table Get-MdbcData -As PS | Format-Table -AutoSize | Out-String # Query a document by _id using a query expression $data = Get-MdbcData (New-MdbcQuery _id -EQ 1) $data # Update the document, set the 'value' to 100 $data._id | Update-MdbcData (New-MdbcUpdate -Set @{value = 100}) # Query the document using a simple _id query Get-MdbcData $data._id # Remove the document $data._id | Remove-MdbcData # Count remaining documents, 1 is expected Get-MdbcData -Count |