Powershell查询MongoDB

kxe2p93d  于 2023-02-07  发布在  Go
关注(0)|答案(4)|浏览(131)

1)下面是我的模式:

{
    "_id" : ObjectId("53f4db1d968166157c2d57ce"),
    "init" : "SJ",
    "name" : "Steve Jobs",
    "companies" : [ 
        {
            "_id" : ObjectId("53f4db1d968166157c2d57cf"),
            "ticker" : "AAPL",
            "compname" : "Apple"
        }, 
        {
            "_id" : ObjectId("53f4db1d968166157c2d57d0"),
            "ticker" : "MSFT",
            "compname" : "Microsoft"
        }, 
        {
            "_id" : ObjectId("53f4db1d968166157c2d57d1"),
            "ticker" : "ABC",
            "compname" : "iTunes"
        }, 
        {
            "_id" : ObjectId("53f4db1d968166157c2d57d2"),
            "ticker" : "DEF",
            "compname" : "iPad Mini"
        }
    ]
}

我正在尝试用Powershell和MongoDB得到一个计算机名列表。以下是我目前得到的:

$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)

$query['init'] = "SJ"
$results = $collection.FindOne($query)
foreach ($result in $results) {
    write-host $result["companies.ticker"] /// Doesn't show me any records
}

这没有显示任何记录。如何显示companies. ticker info where init ="SJ"?
2)顺便说一句,我得到以下错误后

$query['init'] = "SJ"

误差

Cannot index into a null array.
At line:9 char:1
+ $query['init'] = "SJ"
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

知道为什么吗?我只有MongoDB的标准索引,它在"_id"上,没有别的。我的powershell脚本仍然工作,但是我很好奇为什么我会得到这个错误。

  • *[更新第2部分]**感谢@arco444,我在第2部分中不再遇到错误。以下是我修改后的代码:
$query = @{'init' = "SJ"}
$collection.FindOne([MongoDB.Driver.QueryDocument]$query)

但是我实际上需要第1部分的帮助--那就是只显示特定init的公司股票代码。

  • *[ANSWER Part 1]**再次感谢@arco444为我指明了正确的道路。经过一些修补,我发现了我遗漏的地方。以下是我更新的代码:
$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)

$query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated
$results = $collection.FindOne($query)
foreach ($result in $results["companies"]) { /// Updated
    write-host $result["ticker"] /// Updated
}
iyfjxgzm

iyfjxgzm1#

通过阅读MongoDB文档,您似乎需要首先正确地初始化查询对象。

$query = new-object MongoDB.Driver.QueryDocument("init","SJ")
$results = $collection.FindOne($query)
nnt7mjpx

nnt7mjpx2#

下面是我的更新代码:

$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)

$query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated
$results = $collection.FindOne($query)
foreach ($result in $results["companies"]) { /// Updated
    write-host $result["ticker"] /// Updated
}
hgqdbh6s

hgqdbh6s3#

所以当我使用查询过程时

$mongoDbDriverPath = 'D:\mongo\driver\'
$mongoServer = 'myserver:27000'

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

$databaseName = 'Tickets'
$collectionName = 'MongoUserTicket'

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

$query = new-object Mongodb.driver.querydocument('Id','5')
$query2 = New-object Mongodb.driver.querydocument('Type','User')
$results = @()
foreach($item in $collection.Find($query))
{
    $results += $item
}

查询得到意外结果:当管道获取成员的结果,我得到这个:

TypeName: MongoDB.Bson.BsonElement

Name        MemberType Definition                                                                                                                                    
----        ---------- ----------                                                                                                                                    
Clone       Method     MongoDB.Bson.BsonElement Clone()                                                                                                              
CompareTo   Method     int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other)                         
DeepClone   Method     MongoDB.Bson.BsonElement DeepClone()                                                                                                          
Equals      Method     bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other)
GetHashCode Method     int GetHashCode()                                                                                                                             
GetType     Method     type GetType()                                                                                                                                
ToString    Method     string ToString()                                                                                                                             
Name        Property   string Name {get;}                                                                                                                            
Value       Property   MongoDB.Bson.BsonValue Value {get;set;}

当在shell提示符下输入$results时,我得到了预期的数据:

$results 

Name                   Value                                                                                                                                                                                               
----                   -----                                                                                                                                                                                               
Id                 5
AccessToken            
CreatedOn              2013-09-27T22:05:52.246Z                                                                                                                                                                            
TokenExpiration  2013-09-27T22:20:52.246Z                                                                                                                                                                            
RefreshTokenExpiration 2013-09-28T22:05:52.246Z                                                                                                                                                                            
ProfileToken           BsonNull                                                                                                                                                                                            
Type              User                                                                                                                                                                                             
Id                 5
AccessToken            
CreatedOn              2013-09-27T23:42:28.492Z                                                                                                                                                                            
TokenExpiration  2013-09-27T23:57:28.492Z                                                                                                                                                                            
RefreshTokenExpiration 2013-09-28T22:06:04.071Z                                                                                                                                                                            
ProfileToken           BsonNull                                                                                                                                                                                            
Type              User
voj3qocg

voj3qocg4#

这就是我得到一个可以操作的对象的原因:

$results = @()
foreach($item in $collection.Find($query))
{
    $props = @{}
    $item | foreach { $props[ $_.name ] = $_.value }
    $pso = [pscustomobject]$props
    $results += $pso
}

完整代码:

$mongoDbDriverPath = 'D:\mongo\driver\'
$mongoServer = 'myserver:27000'

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

$databaseName = 'Tickets'
$collectionName = 'MongoUserTicket'

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

$query = new-object Mongodb.driver.querydocument('Id','5')
$query2 = New-object Mongodb.driver.querydocument('Type','User')
$results = @()
foreach($item in $collection.Find($query))
{
    $props = @{}
    $item | foreach { $props[ $_.name ] = $_.value }
    $pso = [pscustomobject]$props
    $results += $pso
}
$results

相关问题