0

我正在为 mongo db 使用 alex bilbie 库(https://github.com/alexbilbie/codeigniter-mongodb-library/tree/v2)。我不知道如何用这个库形成 elemMatch 查询。

我需要将其转换为 alexs lib。

db.centers.find(
    {
        '_id': ObjectId('516d3ae30074d35600000001')
    },
    {
        'locations' : {
            '$elemMatch' : { "id" : ObjectId("51b595eabe55b59630000000") }
        }
     }
)
4

2 回答 2

1

解决方案是:

  $m = new Mongo();
  $collection = $m->selectDB('production')->selectCollection("centers");
  $array = array('_id' => new MongoId('516d3ae30074d35600000001'));
  $project = array(
    'locations' => array(
      '$elemMatch' => array('id' =>  new MongoId('51b595eabe55b59630000000'))
     )
   );

    $cursor = $collection->find($array, $project);
    foreach ($cursor as $doc) {
        print_r($doc);
    }

正如 Alex lib 所说:您需要将 $project 数组放在 select 方法中,而不是在 where

于 2013-06-11T11:05:48.233 回答
0

根据他的 repo 中的文档,这对您不起作用:

$this->mongo_db
->where(array(
    '_id' => ObjectId('516d3ae30074d35600000001'),
    'locations' => array( '$elemMatch' => array( "id" : ObjectId("51b595eabe55b59630000000") ) )
))
->get('centers');

编辑:我最初是根据您问题中的查询复制此内容的。你确定你的id财产$elemMatch不应该_id吗?

于 2013-06-10T15:29:59.823 回答