如果使用php,当前日期在mongodb中的开始日期和结束日期之间查找数据

时间:2013-10-01 06:32:53

标签: php mongodb

我在MongoDB中有一个名为shop

的集合
shop{
    "_id" : "523c1e",
    "address" : "100, University Road",
    "city" : "xyz",
    "contact_name" : "John",
    "deals" : [ 
        {
            "deal_id" : "524913",
            "deal_type" : "Sale",
            "deal_description" : "Very good deal",
            "start_date" : "2013-09-12",
            "end_date" : "2013-09-31"
        }, 
        {
            "deal_id" : "52491abf6",
            "deal_type" : "Sale",
            "deal_description" : "Buy 2 jeans, get one free",
            "start_date" : "2013-09-20",
            "end_date" : "2013-10-31"
        }
    ],
   }

我想找到正在运行的交易(当前日期为'2013-10-01')和_id =“523c1e”使用mongodb和php,

所以我会得到,

       {
            "deal_id" : "52491abf6",
            "deal_type" : "Sale",
            "deal_description" : "Buy 2 jeans, get one free",
            "start_date" : "2013-09-20",
            "end_date" : "2013-10-31"
        }

请帮我纠正这个问题,

我正在尝试这个,但没有提供任何输出

<?php
    date_default_timezone_set('Asia/Kolkata');
    $date=date('Y-m-d');

          $pro_id='523c1e';

         $cursor = $collection->find(array("_id" => "$pro_id",$date => array('$gt' => 'deals.start_date','$lte' => 'deals.end_date')),array("deals" => 1));
         foreach($cursor as $document)
         {
              echo json_encode(array('posts'=>$document));
         }
  ?>

请帮帮我......

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,您是否只尝试返回符合搜索条件的子文档?

这是通过在投影中使用positional $ operator来完成的。

$criteria = array("some.nested.structure" => 42);
$project  = array("some.$.structure" => 1);
$collection->find($criteria, $project);

对于您的情况,这将是:

$criteria = array(
    "_id" => $pro_id,
    "deals.start_date" => array('$lte' => $date),
    "deals.end_date" => array('$gt' => $date)
);
$project = array("deals.$" => 1);
$cursor = $collection->find($criteria, $project);

请注意,您的搜索查询错误。 你不能说value =&gt; array(operator =&gt; fieldname),那根本就不是MongoDB语法。 有关如何使用$ lt运算符

的信息,请参阅http://docs.mongodb.org/v2.2/reference/operator/query/lt/