Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Using MongoDB: selecting a document by its ObjectID
  • I'm trying to understand how to use MongoDB with FuelPHP.. Can someone clerify how to select a document based on its ObjectID? I understand that the support for MongoDB is minimal, but I'm hitting such a basic problem that I fear I may be doing something wrong. For example, I have a collection called 'things'. I want to select a thing based on its object id. How come the query below does not produce a result? I know that an object does exist with the given ID:
    $mongodb = \Mongo_Db::instance('default');
    
    $mongodb->where(array('_id' => '4ed5dd5e76621f7758000000'));
    
    $result = $mongodb->get('things');
    
    Log::debug('Found this thing: ' . print_r($result, true));
    

    I looked at the core/classes/mongo/db.php and it seems like all of the where conditions are cast to (string), but as far as I've read, the _id is actually an object of type MongoId. I think you guys understand what I'm trying to say here, so how do you guys do it? Shouldn't the where() methods for this class pickup the _id key and treat the value as a MongoId?, Perhaps reshaping the where to something like (which appears to work for me):
    public function where($wheres = array())
    {
        foreach ($wheres as $wh => $val)
        {
            Log::debug("WHERE: $wh => $val");
            if($wh == '_id')
            {
                $this->wheres[$wh] = new \MongoId($val);
            } else
            {
                $this->wheres[$wh] = (string) $val;
            }
    
        }
        return $this;
    }
    
  • Harro Verton wrote on Wednesday 21st of December 2011:
    On which version of FuelPHP are you? This has been corrected some time ago. https://github.com/fuel/core/blob/1.1/develop/classes/mongo/db.php#L296

    I use V1.1, the same version of this file.
  • So where is it exactly still cast to string? @jsidhu's code snippet is clearly pre v1.1 code...
  • The problem is that this code
    $mongodb->where(array('_id' => '4ed5dd5e76621f7758000000'));
    

    returns no results
  • Ok, found it:
    $mongodb->where(array('_id' => new \MongoId('4ed5dd5e76621f7758000000')));
    
  • I face the exact same problem.
  • On which version of FuelPHP are you? This has been corrected some time ago. https://github.com/fuel/core/blob/1.1/develop/classes/mongo/db.php#L296
  • Thanks @lexx. You saved me a lot of time today.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion