Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 294
Rainbard Avatar asked Dec 17 '12 22:12

Rainbard


People also ask

How do you do greater than or equal to in MongoDB?

MongoDB provides different types of comparison operators and greater than equals to operator($gte) is one of them. This operator is used to select those documents where the value of the field is greater than equals to(>=) the given value. You can use this operator in methods (like, find(), update(), etc.)

Which of the following operator is used to check greater than or equal to MongoDB?

$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .) For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type.

Which of the following operator is used to check greater than or equal to in MongoDB Mcq?

MongoDB (>=) greater than equal to operator - $gte.


1 Answers

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.

like image 88
paulmelnikow Avatar answered Oct 05 '22 16:10

paulmelnikow