0

i am using alex bilbie library for mongo db (https://github.com/alexbilbie/codeigniter-mongodb-library/tree/v2). I dont know how to form elemMatch query with this lib.

I need to transform this to alexs lib.

db.centers.find(
    {
        '_id': ObjectId('516d3ae30074d35600000001')
    },
    {
        'locations' : {
            '$elemMatch' : { "id" : ObjectId("51b595eabe55b59630000000") }
        }
     }
)
Ascherer
  • 8,223
  • 3
  • 42
  • 60
j6c
  • 39
  • 1
  • 8

2 Answers2

1

The solution is:

  $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);
    }

As Alex lib goes: you need to put $project array in select method not in where

j6c
  • 39
  • 1
  • 8
0

Based on the documentation in his repo, does this not work for you:

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

edit: I had originally copied this based on the query in your question. Are you sure that the id property in your $elemMatch shouldn't be _id?

kmfk
  • 3,821
  • 2
  • 22
  • 32
  • Unfortunately no. Results in terminal is different from php. – j6c Jun 10 '13 at 15:45
  • @j6c you should take a look at the actual query that builds for you. A fter the code above, add in a `print_r( $this->mongo_db->last_query() );`. This library just wraps the native php drivers `find` method, in which case that query should work. – kmfk Jun 10 '13 at 15:52
  • id field is correct. i found that also pure php without lib doesn't work as aspected. $m = new MongoClient(); $db = $m->selectDB('local'); $collection = new MongoCollection($db, 'centers'); $array = array('_id' => new MongoId('516d3ae30074d35600000001'), 'locations' => array('$elemMatch' => array('id' => new MongoId('51b595eabe55b59630000000')))); $cursor = $collection->find($array); foreach ($cursor as $doc) { print_r($doc); } – j6c Jun 11 '13 at 10:07