1

I can not get my query in powershell to work for a date range. below is my mongodb doc and powershell code. I have to switch to UTC time to match the time in mongodb. I have tried several different date formats and still can not find any records when querying for a date range or even a specific date. Any help would be appreciated.

MongoDB:

{ 
"_id" : ObjectId("570d0955ef8ca41768d887a8"), 
"HostName" : "blah.foo.bar", 
"Maintenance" : false, 
"Process" : false, 
"ProcessDateTime" : ISODate("2016-04-12T14:39:53.000+0000")
}

Powershell:

$mongoDbDriverPath = "C:\utilities\mongoDB\"
$dbName = "blahProd"
$collectionName = "blah"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Driver.dll"
$db = [MongoDB.Driver.MongoDatabase]::Create("mongodb://localhost/($dbname)")
$collection = $db[$collectionName]

$rundate = Get-Date
$rundate = $rundate.AddMinutes(-30)
$rundate_utc = $rundate.ToUniversalTime()
$ISOrundate_utc = $rundate_utc.ToString("yyyy-MM-ddTHH:mm:ssZ")

$query =[MongoDB.Driver.Builders.Query]::GTE"ProcessDateTime",$ISOrundate_utc)

$results = $collection.find($query)
foreach ($result in $results) {
    write-host $result["HostName"] " - " $result["ProcessDateTime"]
}
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
Ross Jurek
  • 11
  • 1
  • it could be easier using c# code inside power shell script - [see this](http://stackoverflow.com/a/35865663/5919473) – profesor79 Apr 15 '16 at 15:13

1 Answers1

0
$query2 = [MongoDB.Driver.Builders.Query]::GTE("Time", [dateTime]"2021-06-01")
$query3 = [MongoDB.Driver.Builders.Query]::LT("Time", [dateTime]"2021-06-09")

seems to do the trick.

  • Could you add more context to your answer like what was missing in the OPs implementation and why this would work better? – rahul.taicho Jun 13 '21 at 06:59