Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect MongoDB with PowerShell?

I already tried with the following code:

$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?

like image 687
Dhanasekaran M Avatar asked Oct 17 '22 09:10

Dhanasekaran M


1 Answers

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:

Install-Module Mdbc 

Step 2: In a PowerShell command prompt import the module:

Import-Module Mdbc 

Step 3: Take a look at help:

help about_Mdbc 
help Connect-Mdbc -full

Then go through the following steps to see if the setup is working:

# 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
like image 120
Husk Rekoms Avatar answered Oct 30 '22 01:10

Husk Rekoms