Travis Ryan
Travis Ryan

Reputation: 1

Want to query for only time part of a MongoDate in MongoDB

I have searched around quite a bit and hopefully someone can help me out.

I already know how to query documents that are 3 hours ago, etc. I want to query for all documents from all days from 11am to 1pm, etc.

Anyone know an easy way to do this? Or a more complex Map/Reduce I can use?

I'd rather this not be dependent upon a specific programming language if possible, but would if it must I'd like it to be in PHP. It's usually better to have this done in the database.

Upvotes: 0

Views: 165

Answers (1)

chx
chx

Reputation: 11760

MongoDB, in general, has only a few simple operators. With a twist: if you need a lot, you can always turn to JS. So doing that, you need to run a $where. http://www.php.net/manual/en/mongocollection.find.php has examples.

$js = "function() {
  var date = new Date(this.datecolumn);
  return date.getHours() >= 11 && date.getHours() <= 13;
}";
$collection->find(array('$where' => $js));

Upvotes: 1

Related Questions