1

1) Here's my schema:

{
    "_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"
        }
    ]
}

I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far:

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

This doesn't show me any records. How can I display companies.ticker info where init = "SJ"?

2) Btw, I get the following error after

$query['init'] = "SJ"

error

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

Any ideas as to why? I only have the MongoDB's standard index, which is on "_id", nothing else. My powershell script still works but I'm curious as to why I get that error.

[UPDATE Part 2] Thanks to @arco444, I no longer get error in part 2. Here's my revised code:

$query = @{'init' = "SJ"}
$collection.FindOne([MongoDB.Driver.QueryDocument]$query)

But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one?

[ANSWER Part 1] Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code:

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

4 Answers 4

1

From reading the MongoDB documentation, it looks like you need to initialise the query object properly first. Try this:

$query = new-object MongoDB.Driver.QueryDocument("init","SJ")
$results = $collection.FindOne($query)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That eliminated that error. But could you shed some light on how to display the company tickers using powershell?
0

Here's my updated code:

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

Comments

0

So when I use your query procedure with

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

I get unexpected results for the query: When piping to Get member for results I get this:

   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;}    

When entering $results on the shell prompt I get the data I expect:

$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 

Comments

0

here is what allowed me to get an object that i could operate on:

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

full code:

    $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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.