Php 如何在MongoDb中使用$where查找子文档
集合包含如下数据Php 如何在MongoDb中使用$where查找子文档,php,mongodb,Php,Mongodb,集合包含如下数据 { '_id': ObjectId("527cf8ae3ad5a461caf925fc"), 'name': { 'first': 'John', 'last': 'Backus' } } 我想通过$where查找名为“John”的记录 $m = new MongoClient(); $db = $m->selectDB('school');
{
'_id': ObjectId("527cf8ae3ad5a461caf925fc"),
'name': {
'first': 'John',
'last': 'Backus'
}
}
我想通过$where查找名为“John”的记录
$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));
我有个例外
捕获到异常:localhost:27017:TypeError:无法读取“this.name.first==”Jo'附近未定义的属性“first”
我只想用$where搜索。这真是一个奇怪的场景。如果你能找到它,你为什么要这么做
db.collection.find({'name.first' : 'John'})
无论如何,错误在first.name
中,并且您的集合具有架构name.first
$js = "function() {
return this.name.first == 'John';
}";
基本上,它试图告诉您“我正在查看字段名,但它未定义,然后当我检查字段时,第一个未定义的字段就崩溃了。”这对我很有效:
$m = new MongoClient();
$db = $m->school;
$collection = $db->student;
$cursor = $collection->find( array('name.first' => 'John' ));
foreach ($cursor as $document) {
var_dump($document);
}
@Salvandor这是可能的或不是通过$where,因为我知道如何才能找到其他使用方法没有得到你。我只是告诉你你的错误在哪里,并告诉你如何修复它。真的很难理解你在键入什么。。。仔细看一下我的代码,你会发现其中的区别。@NanheKumar我已经读过这个链接,但这里没有这样的例子。为什么要在这个场景中使用$where?@AsyaKamsky:因为这适合需求条件。@ParnitDas抱歉,我不知道这是什么意思。要求条件是什么?