如何在MongoDB中使用$where查找子文档


How can find Subdocuments using $where in MongoDb

集合包含这样的数据

    {
        '_id': ObjectId("527cf8ae3ad5a461caf925fc"),
        'name': {
            'first': 'John',
            'last': 'Backus'
        }
    }

我想找到名字"约翰"到$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));

我收到异常 捕获异常:本地主机:27017:类型错误:无法读取"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);
   }