简体   繁体   English

Mongodb php查询,在数组中搜索?

[英]Mongodb php query, search in array?

I am looking for a way to search for a keyword (ex. "Henrik") in the "answers" array of documents with the following structure 我正在寻找一种方法来搜索具有以下结构的“answers”文档数组中的关键字(例如“Henrik”)

Array
(
[_id] => MongoId Object
    (
        [$id] => 4eeedd9545c717620a000007
    )

[formId] => 6
[respId] => 4eeedd95c93228
[dateCreated] => 2011-10-14 07:45
[answers] => Array
    (
        [field1] => Henrik
        [field6] => myemail@domain.com
        [field7] => my city address
    )

)

I am working in PHP on this project, and quering like this works of course: 我在这个项目上使用PHP工作,当然这样查询:

$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. 我无法在此处或在Google上找到任何关于此的示例。

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". 我认为你想要做的是在“答案”中的文档的任何字段中查找“Henrik”。 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')));
$answers = $collection->find( array('formId' => 6, 
           'answers'=>
                      array('$in' => array('Henrik'))));

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: 不是解决方案,而是解决方法:假设您的密钥与field1,field6一样任意,您可以停止使用密钥并将值存储在普通数组中:

'answers' => array(
    'Henrik',
    'myemail@domain.com',
    '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. 会找到'Henrik'是其中任何一个答案的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM