MONGODB - PHP。在多个嵌套数据字段中查询

时间:2014-09-19 15:59:16

标签: php mongodb

这里是我的数据的示例:

 '_id' => new MongoId("54087e076c03943c3c8b456b"),
        'fornitureFuture' => 
      array (
        '0' => 
        array (
          'data_start'▼ => new MongoDate(1412114400, 0),
          'data_end' => new MongoDate(1414710000, 0),
          'f1' => '65',
          'f2' => new MongoInt32(0),
          'f3' => '45',
          'fornitore' => new MongoId("5346cb2ab9d6f0021e6b18a0"),
        ),
        '1' => 
        array (
          'data_start' => new MongoDate(1420066800, 0),
          'data_end' => new MongoDate(1427752800, 0),
          'f1' => '63.75',
          'f2' => new MongoInt32(0),
          'f3' => '70.4',
          'fornitore' => new MongoId("533406896c0394a62c8b4569"),
        ),

我需要在data_start和data_end之间查找fornitureFuture中是否存在与MongoDate相关的数据...

第一组data_start是10/01/2014和data_end 10/31/2014
第二组data_start是01/01/2015和data_end 03/31/2015

类似的东西:

//today is 09/19/2014 

$dataTest = mktime(0,0,0,date('n')+2,14,date('Y'));   //return 11/14/2014

$testMese = $this->db->getOne('MyCollection', array('_id'=> new \MongoId($thisPodPdr['_id']), 'fornitureFuture.data_start'=>array('$lte'=> new \MongoDate($dataTest)) , 'fornitureFuture.data_end'=>array('$gt'=> new \MongoDate($dataTest))   ) , array('fornitureFuture'=>1) );

我期待空响应,但返回记录..

2示例:

$dataTest = mktime(0,0,0,date('n')+7,14,date('Y'));   //return 04/14/2015

$testMese = $this->db->getOne('MyCollection', array('_id'=> new \MongoId($thisPodPdr['_id']), 'fornitureFuture.data_start'=>array('$lte'=> new \MongoDate($dataTest)) , 'fornitureFuture.data_end'=>array('$gt'=> new \MongoDate($dataTest))   ) , array('fornitureFuture'=>1) );

正确地返回空白!

我需要在同一个区块中进行测试...类似

'fornitureFuture.$.data_start'=>array('$lte'=> new \MongoDate($dataTest)) , 'fornitureFuture.$.data_end'=>array('$gt'=> new \MongoDate($dataTest))

但是不行。

<\ n> \ is来自命名空间,这个&gt; db-&gt; getOne(collection,$ query,$ fields)是我的函数,如$ this-&gt; collection-&gt; findOne($ query,$ fields); < / p>

没有语法错误。

对不起我的英文并感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你的第一个例子,当你期望没有时会返回2个结果,运行以下查询:

[
  '_id' => new MongoId(...),
  'fornitureFuture.data_start' => ['$lte' => new MongoDate(1418533200)],
  'fornitureFuture.data_end' => ['$gt' => new MongoDate(1418533200)],
]

您提供的示例文档包含两个数组元素,其中包含以下日期范围:

  1. 14121144001414710000
  2. 14200668001427752800
  3. 此文档匹配,因为1412114400(第一个元素)小于14185332001427752800(第二个元素)大于1418533200。只需引用fornitureFuture.data_startfornitureFuture.data_end,如果任何数组元素的子字段符合条件,MongoDB的查询匹配器就会得到满足。

    您可能希望将开始/结束条件限制为相同的数组元素,在这种情况下$elemMatch是您正在寻找的内容:

    [
      '_id' => new MongoId(...),
      'fornitureFuture' => [
        '$elemMatch' => [
            'data_start' => ['$lte' => new MongoDate(1418533200)],
            'data_end' => ['$gt' => new MongoDate(1418533200)],
        ],
      ],
    ]
    

    此标准现在应仅在相同元素的开始/结束日期满足范围时匹配。在相关说明中,您可能还对$投影运算符感兴趣,将fornitureFuture仅限于匹配的元素。