0

Is it possible to query mongodb by matching the keywords or a date range in the record?

For example if I have a collection with fields such as "Title", "Author" and "Date". I have this record with Title as "hello world", author as "john billy", date as "2014/05/12".

Is it possible to return this record by entering either "world" or "billy" or a date range (2014/01/12 to 2014/06/12)

How should I write my query to get the record I want?

Thanks in advance!

below is my code for date period: $from_Id is the

        $rangeQuery = array('timestamp' => array( '$gte' => $from_Id, '$lte' => $to_Id ));

        $cursor = $collection->find($rangeQuery);
hao
  • 635
  • 2
  • 8
  • 20

1 Answers1

1

You'll have to use $lt/$lte (correspond to < / <=) and $gt/$gte (correspond to > / >=) operators to set a date range in your query. Just look for the mongodb documentation :

http://docs.mongodb.org/manual/reference/operator/query-comparison/

Here is an example from the php doc (http://php.net/manual/en/mongocollection.find.php) :

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The link given by @SaTya will help you to make a search with keywords.

magon
  • 81
  • 8
  • Thank you, but I retrieved zero record using this query. Is it because it does not work with date? maybe only work with number? – hao Feb 04 '15 at 09:42
  • It depends on how your dates are stored in your database. If you have timestamps you can use the same query as in the example : `$rangeQuery = array('date' => array('$gt' => 1422745200, '$lt' => 1423004400));` But if you store a string like this one : "2015-02-02" i think that the best way is to convert it into timestamp first and make the query after. – magon Feb 04 '15 at 10:35