Reputation: 5264
this is my php
script for inserting and retrieving data from mongoDB.
in the following the insertion works and find() method works too.
problem is when using condition inside find() method it won't give any results.
why is that?
//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);
}
Upvotes: 1
Views: 121
Reputation: 236
Because with this php script you insert only one object into Mongo. http://php.net/manual/en/mongocollection.insert.php
As a result in Mongo (you can check it with Mongo shell) you have something like this:
{
"_id" : ...,
"0" : {
"test1" : "2",
"test2" : "default"
},
"1" : {
"test1" : "2",
"test2" : "default"
},
"2" : {
"test1" : "3",
"test2" : "default"
},
"3" : {
"test1" : "default",
"test2" : "default"
}
}
From the code you can confirm it by using search condition:
$q = array('0.test1' => '2');
To get desired result you should insert values like this:
$collection->insert($data1);
$collection->insert($data2);
$collection->insert($data3);
$collection->insert($data4);
Upvotes: 1