Mitchel Abrahams
Mitchel Abrahams

Reputation: 42

Why in my case are $gte and $lte not working in mongoDB

I 've got the following document.

{ 
   "_id" : ObjectId("5d0e4232ccfb3ee9ac72a64d"), 
   "arraydatumobject" : {
       "datum" : ISODate("2010-01-02T00:00:00.000+0000")
   }
}

when i try to find the date with either $gte or $lte or even both i cant find the document.

so something like this:

db.getCollection("test").find(
   {
       arraydatumobject : { $elemMatch:{ datum :  {$gte : new ISODate("2008-01-02"), $lte : new ISODate("2011-01-02")}}}
   }
)

or this

db.getCollection("test").find(
    {
        arraydatumobject : {datum :  {$gte : new ISODate("2008-01-02"), $lte : new ISODate("2011-01-02")}}
    }
)

gets me nothing.

But when i use the following i do get a result.

db.getCollection("test").find(
    {
        arraydatumobject : {datum : new ISODate("2010-01-02")}
    }
)

i'm getting the document that i'm searching for...

What am i missing here?

Upvotes: 0

Views: 4339

Answers (2)

Akrion
Akrion

Reputation: 18515

With a given document of:

{ 
   "_id" : ObjectId("5d0e4232ccfb3ee9ac72a64d"), 
   "arraydatumobject" : {
       "datum" : ISODate("2010-01-02T00:00:00.000+0000")
   }
}

Your date range find query should be:

db.getCollection('test').find({ 
 'arraydatumobject.datum': {   // you have an object use obj.prop
    $gte : new ISODate("2008-01-02"), 
    $lte : new ISODate("2011-01-02")
  } 
})

Upvotes: 1

Your second example should work, but you have a pair of curly braces missing there.

Also, you should compare using node.js Dates, not ISODates

Try:

db.getCollection("test").find(
    {
        arraydatumobject : {datum :  {$gte : new Date(2008,2,1), $lte : new Date(2011, 2, 1)}}
    }
)

Upvotes: 0

Related Questions