Collection contains data like this
{
'_id': ObjectId("527cf8ae3ad5a461caf925fc"),
'name': {
'first': 'John',
'last': 'Backus'
}
}
I want find record where first name 'John' through $where
$m = new MongoClient();
$db = $m->selectDB('school');
$collection = new MongoCollection($db, 'student');
$js = "function() {
return this.first.name == 'John';
}";
$cursor = $collection->find(array('$where' => $js));
I am getting exception Caught exception: localhost:27017: TypeError: Cannot read property 'first' of undefined near 'this.name.first=='Jo'
I would like to search only with $where.
This is a really weird scenario. Why would you do this if you can find it with
db.collection.find({'name.first' : 'John'})
Anyway, the error is in the first.name
and your collection has a schema name.first
$js = "function() {
return this.name.first == 'John';
}";
Basically it is trying to tell you that "I am looking into the field name and it is undefined and then when I am checking for a field first of this undefined I crashed".
This worked for me :
$m = new MongoClient();
$db = $m->school;
$collection = $db->student;
$cursor = $collection->find( array('name.first' => 'John' ));
foreach ($cursor as $document) {
var_dump($document);
}