PHP Lithium:过滤现有的DocumentSet并获得第一个Match


PHP Lithium: Filtering an existent DocumentSet and get first Match

我正在从MongoDB中检索Lithium中的DocumentSet,但我不想一次处理所有文档。相反,我想要一个过滤器,我可以告诉这样的东西:

$manyDocuments->giveMeTheOneWhere(array('foo' => 'bar'));

我已经试过这样做了,但没有奏效:

$manyDocuments->find(function($singleDocument){
    return ($singleDocument->foo == 'bar');
});

即使我在闭包中手动返回true,它也总是返回一个空的DocumentSet。

只是为了增加清晰度:我不是在寻找数据库操作,而是想从已经存在的DocumentSet中获得一个。有没有一种奇特的方法可以实现这一点,或者我需要使用自定义函数来遍历集合?

我觉得很对。这就是您正在使用的代码吗
例如,您正在使用的"bar"值是您正在传递的值吗?

我是Lithium主分支的最新成员,写了这个对我有用的单元测试。我真的不知道为什么你会得到一个空的DocumentSet。

$docs = new DocumentSet(array('data' => array(
    new Document(array('data' => array(
        'id' => 1,
        'foo' => 'bar'
    ))),
    new Document(array('data' => array(
        'id' => 2,
        'foo' => 'baz'
    ))),
    new Document(array('data' => array(
        'id' => 3,
        'foo' => 'bar'
    ))),
    new Document(array('data' => array(
        'id' => 4,
        'blah' => 'ack'
    )))
)));
$filtered = $docs->find(function($doc) {
    return $doc->foo === 'bar';
});
$expected = array(
    '0' => array('id' => 1, 'foo' => 'bar'),
    '2' => array('id' => 3, 'foo' => 'bar')
);
$this->assertIdentical($expected, $filtered->data());

我没有使用find(),而是使用了带有闭包的first()。这是意料之中的事。遗憾的是,这是我以前唯一没有尝试过的事情。对不起,我回答了自己的问题。

无论如何,我仍然有兴趣获得另一个文档集。