Search code examples
phpcodeignitermongodband-operator

MongoDB PHP query using $and operator on the same object


I've got a fairly simple query that I have working in command line, and am trying to execute using php.

It's looking for documents that match all of the given "tags" entered in a search box:

db.collection.find( { $and: [ { tags: "cats" }, { tags: "video" } ] } )

I can't seem to figure out how to translate this to php. I've been using codeigniter for everything up to this point (Alex Bilbie's library), but have looked into building my own queries with no luck. Most of the methods I've tried eliminate the first tag (cats), since it is looking at the same field name (tags).

any thoughts?


Solution

  • PHP can be a bit tricky with how you need to format the arrays. What I've found to be the best way to create the queries is through doing things like:

    json_encode($myQuery); 
    

    then comparing that to what actually works directly on the console of the app. In this case you're looking for:

    $item = array('$and' => array(array('tags' => 'cats'), array('tags' => 'videos')))
    

    which you can confirm by doing:

    echo(json_encode(array('$and' => array(array('tags' => 'cats'), array('tags' => 'videos')))));
    

    Good Luck!