0

All:

Im pretty new to MongoDB, I wonder if I want to search document by a date range, how can i do that? So, the question will be:

[1] How can I insert the data?

My data object is like:

{
    value: 10,
    date: "20150121"
}

I want to know how can I preprocess the date field before insert it

[2] How can I search a certain range docuemnts?

I am thinking using something like:

db.collection.find( { date: { $gt: date1, $lt: date2 } } );

But I am not sure.

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201
  • For (1), see https://stackoverflow.com/questions/3778428/best-way-to-store-date-time-in-mongodb and https://stackoverflow.com/questions/6764821/what-is-the-best-way-to-store-dates-in-mongodb, for example. For (2), yes you can use comparison operators - e.g. see https://stackoverflow.com/questions/8835757/return-query-based-on-date and the MongoDB documentation at http://docs.mongodb.org/manual/reference/operator/query/ – DNA May 20 '15 at 22:34

1 Answers1

0

Try it out. That will work. You'll likely want to typecast your date as an integer instead of a string, as shown.

> db.datesort.insert({value:NumberInt(10),date:NumberInt(20150121)});
> db.datesort.insert({value:NumberInt(20),date:NumberInt(20150122)});
> db.datesort.insert({value:NumberInt(30),date:NumberInt(20150123)});
> db.datesort.insert({value:NumberInt(40),date:NumberInt(20150124)});
> db.datesort.insert({value:NumberInt(50),date:NumberInt(20150125)});

> db.datesort.find({date:{$gt:20150121,$lt:20150124}});
{ "_id" : ObjectId("555d0c23f4384ca8c403f441"), "value" : 20, "date" : 20150122 }
{ "_id" : ObjectId("555d0c2bf4384ca8c403f442"), "value" : 30, "date" : 20150123 }
Ben Coffin
  • 483
  • 4
  • 13