Mongodb php query, search in array?

13,606

Solution 1

I don't think it's possible to do that.

"answers", being an array of documents (as you say), needs to know where in the documents it contains to look for the value you specify.

I presume that what you want to do is to look for 'Henrik' on any of the fields of the documents in "answers". In this case I think your best bet is to use $or:

$answers = $collection->find( array('formId' => 6, '$or' => array('answers.field1'=> 'Henrik', 'answers.field6' => 'Henrik', 'answers.field7' => 'Henrik')));

Solution 2

$answers = $collection->find( array('formId' => 6, 
           'answers'=>
                      array('$in' => array('Henrik'))));

Solution 3

Not a solution, but a workaround: assuming your keys are as arbitrary as field1, field6, you could stop using keys and store the values in a normal array:

'answers' => array(
    'Henrik',
    '[email protected]',
    'my city address'
)

In which case your query:

$answers = $collection->find( array('formId' => 6, 'answers'=> 'Henrik' ) );

would find documents where 'Henrik' was any one of the answers.

Share:
13,606
Henkealg
Author by

Henkealg

Updated on June 08, 2022

Comments

  • Henkealg
    Henkealg almost 2 years

    I am looking for a way to search for a keyword (ex. "Henrik") in the "answers" array of documents with the following structure

    Array
    (
    [_id] => MongoId Object
        (
            [$id] => 4eeedd9545c717620a000007
        )
    
    [formId] => 6
    [respId] => 4eeedd95c93228
    [dateCreated] => 2011-10-14 07:45
    [answers] => Array
        (
            [field1] => Henrik
            [field6] => [email protected]
            [field7] => my city address
        )
    
    )
    

    I am working in PHP on this project, and quering like this works of course:

    $answers = $collection->find( array('formId' => 6, 'answers.field1'=> 'Henrik' ) );
    

    What I want to do is search without a specific key of the answers array, like this

    $answers = $collection->find( array('formId' => 6, 'answers'=> 'Henrik' ) );
    

    Is it possible to do this type of query? I am sorry if this is a repost. I was not able to find any examples about this here or on Google.

  • Henkealg
    Henkealg over 12 years
    I guess that is the closest I will come, and it might just work for me to. Thanks!
  • lesolorzanov
    lesolorzanov about 10 years
    This is the correct answer, nowadays the driver works perfect with this