PowerShell 与 MongoDB C# 驱动程序方法不兼容?

2024-05-10

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

Cannot find an overload for "GetCollection" and the argument count: "1".

我可能可以使用其他没有泛型的 GetCollection 方法,但我不知道具体如何。

下面发布的答案指出了一些很好的信息,但不幸的是提供的代码与我已经尝试过的相同,并且它不起作用。

这是我想做的:

我想使用 PowerShell 创建一些文档。 我现在面临的问题似乎是“GetCollection”无法正常工作。我认为这与 Powershell 中缺乏对泛型的支持有关。不管怎样,我找到了一些 CmdLets 来运行通用方法。但我认为这会使代码变得过于复杂。有办法解决这个问题吗?

我看到还有其他不基于 C# 泛型的 GetCollection 方法,但我还不明白如何在 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

上面列出的代码是从早期的 SO 问题复制(并略有更改)的:Powershell Mongodb 身份验证 https://stackoverflow.com/questions/27695670/powershell-mongodb-authentication

有什么建议如何做到这一点吗?我假设 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

我希望这仍然有一些帮助,这对我使用最新的 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])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PowerShell 与 MongoDB C# 驱动程序方法不兼容? 的相关文章

随机推荐