1

这是我php从 mongoDB 插入和检索数据的脚本。在下面的插入工作和 find() 方法也工作。问题是在 find() 方法中使用条件时,它不会给出任何结果。这是为什么?

//object class
class data{
    public $test1 = "default";
    public $test2 = "default";
}

//creating 4 objects and change some values and insert to DB
$data1 = new data();
$data1->test1 = '2';

$data2 = new data();
$data2->test1 = '2';

$data3 = new data();
$data3->test1 = '3';

$data4 = new data();

$collection->insert([$data1, $data2, $data3, $data4]);

//viewing all (this is works - retrieve all inserted data)
$res = $collection->find();

foreach($res as $val){
    var_dump($val);
}


//retrieve with condition (not works)
$q = array('test1' => '2');

$res2 = $collection->find($q);

foreach($res2 as $val2){
    var_dump($val2);
}
4

1 回答 1

1

因为使用这个 php 脚本,您只需将一个对象插入 Mongo。http://php.net/manual/en/mongocollection.insert.php

结果在 Mongo 中(你可以用 Mongo shell 检查它)你有这样的东西:

{
"_id" : ...,
"0" : {
    "test1" : "2",
    "test2" : "default"
},
"1" : {
    "test1" : "2",
    "test2" : "default"
},
"2" : {
    "test1" : "3",
    "test2" : "default"
},
"3" : {
    "test1" : "default",
    "test2" : "default"
}

}

从代码中,您可以使用搜索条件进行确认:

$q = array('0.test1' => '2');

要获得所需的结果,您应该插入如下值:

$collection->insert($data1);
$collection->insert($data2);
$collection->insert($data3);
$collection->insert($data4);
于 2016-02-01T11:23:42.397 回答