-2

I have a collection in MongoDB called 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"
        }
    ],
   }

I want to find deals which is now running(for current date '2013-10-01') and _id="523c1e" using mongodb and php,

So I will get,

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

please help me to right this query,

I am trying this one but not give any output

<?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));
         }
  ?>

Please help me...

4

1 回答 1

1

如果我正确理解了这个问题,您是否试图仅返回与搜索条件匹配的子文档?

这是通过在投影中使用位置 $ 运算符来完成的。

$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 => array(operator => fieldname),那根本不是 MongoDB 语法。有关如何使用 $lt 运算符的示例,请参见http://docs.mongodb.org/v2.2/reference/operator/query/lt/

于 2013-10-22T23:53:40.033 回答