Rainbard
Rainbard

Reputation: 341

How can I find records greater than or equal to a time in MongoDB?

I have a MongoDB document structured like this:

{
"_id": ObjectId("50cf904a07ef604c8cc3d091"),
"lessons": {
    "0": {
        "lesson_name": "View and Edit Lists",
        "release_time": ISODate("2012-12-17T00:00:00Z"),
        "requires_anim": false,
        "requires_qq": true
    },
    "1": {
        "lesson_name": "Leave a Tip",
        "release_time": ISODate("2012-12-18T00:00:00Z"),
        "requires_anim": false,
        "requires_qq": true
    }
}
}

I have a number of such documents. I'd like to get all documents for which the release time of a lesson is greater than or equal to a given time. Here's the query I wrote:

db.lessons.find({"lessons.release_time":{"$gte": ISODate("2012-12-16")}});

But this is not returning any documents. Any ideas on what I'm doing wrong and how to correct it. Thanks.

Upvotes: 9

Views: 35020

Answers (1)

paulmelnikow
paulmelnikow

Reputation: 17218

Here's the result of my testing:

> db.testc.insert( { lessons: [
     {release_time: ISODate("2012-12-17T00:00:00Z")},
     {release_time: ISODate("2012-12-18T00:00:00Z")}
  ] } )
> db.testc.find({"lessons.release_time":{"$gte": ISODate("2012-12-16")}})
{ "_id" : ObjectId("50cfa093ab08a4592c73f927"),
  "lessons" : [
      { "release_time" : ISODate("2012-12-17T00:00:00Z") },
      { "release_time" : ISODate("2012-12-18T00:00:00Z") }
   ] }

Your query is fine but, as others have pointed out, most likely your data is not structured as an array.

Upvotes: 17

Related Questions