PowerShell与MongoDB C#Driver的方法不兼容?

Mat*_*ost 4 c# generics powershell mongodb

由C#Generics引起的最新MongoDB驱动程序的问题:

Cannot find an overload for "GetCollection" and the argument count: "1".
Run Code Online (Sandbox Code Playgroud)

我可能在没有泛型的情况下使用其他GetCollection方法,但我不知道具体如何.

更进一步说明的答案指出了一些很好的信息,但不幸的是,提供的代码与我已经尝试过的相同,并且无法正常工作.

这是我想做的事情:

我想使用PowerShell创建一些文档.我现在面临的问题似乎是"GetCollection"无法正常工作.我认为这与Powershell中缺乏对泛型的支持有关.无论如何,我发现一些CmdLets来运行泛型方法.但我认为这会使代码过于复杂.有办法解决这个问题吗?

我看到有其他的GetCollection方法不是基于C#Generics,但我还不了解如何在PowerShell中使用它们.

Powershell例外: Cannot find an overload for "GetCollection" and the argument count: "1"

# Mongo DB driver
Add-Type -Path 'CSharpDriver-2.0.1\MongoDB.Bson.dll'
Add-Type -Path 'CSharpDriver-2.0.1\MongoDB.Driver.dll'

# Conncetion to MongoDB
$connectionString = "mongodb://localhost:27018"
$db =  "TestDB"
$collection =  "Test"


function Get-MongoDBCollection ($connectionString, $db, $collection)
{
   $mongoClient = New-Object MongoDB.Driver.MongoClient($connectionString)
   $mongoDatabase = $mongoClient.GetDatabase($db)
   $mongoCollection = $mongoDatabase.GetCollection($collection)
   return $mongoCollection
}


# Connect to MongoDB and get collection
$mongoCollection = Get-MongoDBCollection $connectionString $db $collection
Run Code Online (Sandbox Code Playgroud)

上面列出的代码是从早期的SO问题中复制(并稍微更改过):Powershell Mongodb身份验证

有什么建议可以这样做吗?我假设SO中列出的代码基于早期的驱动程序版本.我认为这就是它不再工作的原因.

PowerShell控制台上的完整执行:

Cannot find an overload for "GetCollection" and the argument count: "1".
At F:\PowerShell\CreateDB.ps1:31 char:3
+   $mongoCollection = $mongoDatabase.GetCollection($collection)
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
Run Code Online (Sandbox Code Playgroud)

小智 9

我希望这仍然可以提供一些帮助,这对我来说最新的C#驱动程序和当前的MongoDB RC-4.

function Get-MongoDBCollection {
Param(
    $database,
    $CollectionName,
    $settings = $null, #[MongoDB.Driver.MongoCollectionSetting]
    $returnType = [PSOBJECT]
)
    $method = $database.GetType().GetMethod('GetCollection')
    $gericMethod = $method.MakeGenericMethod($returnType)
    $gericMethod.Invoke($database,[object[]]($CollectionName,$settings))
}
$Collection = Get-MongoDBCollection $database 'test'
# or 
$Collection = Get-MongoDBCollection $database 'test' -returnType  ([MongoDB.Bson.BsonDocument])
Run Code Online (Sandbox Code Playgroud)