【问题标题】:How to read mongodb 5.0 collections in powershell如何在 powershell 中读取 mongodb 5.0 集合
【发布时间】:2021-11-02 20:26:04
【问题描述】:

我正在尝试使用 powershell 和以下代码读取 mongodb5.0 中的集合文档。

最后一行出现错误$collection.find($query)

方法调用失败,因为 [MongoDB.Driver.MongoCollectionImpl`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]] 不包含名为 '寻找'。

function Get-MongoDBCollection {
Param(
    $database,
    $CollectionName,
    $settings = $null, #[MongoDB.Driver.MongoCollectionSetting]
    $returnType = [PSOBJECT]
)
    $method = $database.GetType().GetMethod('GetCollection')
    $GenericMethod = $method.MakeGenericMethod($returnType)
    $GenericMethod.Invoke($database,[object[]]($CollectionName,$settings))
}

$mongoDbDriverPath = 'C:\Users\testuser\'
$mongoServer = 'localhost:27017'

Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll"

add-type -path "$mongoDbDriverPath\System.Runtime.InteropServices.RuntimeInformation.dll"
Add-Type -Path "$mongoDbDriverPath\MongoDB.Bson.dll"
Add-Type -Path "$mongoDbDriverPath\MongoDB.Driver.dll"
add-type -path "$mongoDbDriverPath\DnsClient.dll";
#Add-Type -path "$mongoDbDriverPath\MongoDb.Driver.Core.dll"    
Add-Type -Path "$mongoDbDriverPath\MongoDB.Libmongocrypt.dll"
Add-Type -Path "$mongoDbDriverPath\System.ValueTuple.dll"

$databaseName = 'myDatabase'
$collectionName = 'myCollection'

$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer"
$database = $client.GetDatabase($databaseName)

$Collection = Get-MongoDBCollection $database $collectionName
#$Collection = Get-MongoDBCollection $database $collectionName -returnType  ([MongoDB.Bson.BsonDocument])

$query = new-object MongoDB.Bson.BsonDocument('Name','john')

$collection.find($query)

【问题讨论】:

    标签: c# mongodb powershell collections


    【解决方案1】:

    Find 是一种扩展方法,与 C# 编译器不同,PowerShell 无法弄清楚如何解决这些问题。您必须引用定义扩展方法的底层静态类型来调用它:

    [MongoDb.Driver.IMongoCollectionExtensions]::Find($collection, $query)
    

    但由于Find 也是通用的,我们需要使用MakeGenericType() 的等效方法来创建我们可以调用的特定于类型的版本:

    function Find-MongoDbDocument
    {
      param(
        [Parameter(Mandatory = $true, Position = 0)]
        [MongoDB.Driver.IMongoCollection[MongoDB.Bson.BsonDocument]]
        $collection,
    
        [Parameter(Position = 1)]
        [MongoDB.Driver.FilterDefinition[MongoDB.Bson.BsonDocument]]$filter = $null,
    
        [ValidateRange(1,100000)]
        [int]$Limit
      )
    
      $documentType = [MongoDB.Bson.BsonDocument]
    
      # Discover the relevant Find() extension method overload
      $findDefinition = [MongoDB.Driver.IMongoCollectionExtensions].GetMethods() |Where-Object {$_.Name -eq 'Find' -and $_.GetParameters().Count -eq 3} |Select-Object -First 1
    
      # Make a type-parameter-specific version of Find() 
      $findBsonMethod = $findDefinition.MakeGenericMethod($documentType)
    
      # Invoke Find()
      $result = $findBsonMethod.Invoke($null, @($collection, $filter, $null))
    
      # Limit the result set size, if requested
      if($PSBoundParameters.ContainsKey('Limit')){
        $result = $result.Limit($Limit)
      }
    
      # Fetch the results
      $cursor = $result.ToCursor()
      while($cursor.MoveNext([System.Threading.CancellationToken]::None)){
        Write-Output $cursor.Current 
      }
    }
    

    注意,我使用 [BsonDocument] 而不是 [psobject] 作为文档类型 - MongoDB 驱动程序已经原生支持反序列化为 [BsonDocument](但不是 [psobject])。

    这样使用:

    # Obtain collection object 
    $collection = Get-MongoDBCollection $database $collectionName -returnType $([MongoDB.Bson.BsonDocument])
    
    # Define filter
    $filter = [MongoDB.Bson.BsonDocument]::new('Name', 'John')
    
    # Fetch first 100 matching documents
    Find-MongoDbDocument -Collection $collection -Filter $filter -Limit 100
    

    【讨论】:

    • 感谢您的回复,但它给出了同样的错误。你能给我提供完整的代码来使用 .net 驱动程序 2.13.1(MongoDB shell 版本 v5.0.2 和 PowerShell 版本 5.0)阅读文档
    • 对此有何回应?我正在等待这个解决方案>
    • @kuldeepSingh 我用更完整的例子更新了答案
    • 非常感谢。它解决了我的问题。再一次感谢你。上帝保佑你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2023-04-10
    • 2017-02-12
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多