douao3636 2017-01-04 14:48
浏览 45
已采纳

搜索MongoDB中的所有集合数组

I have a nested array of values that look like this in RoboMongo;

enter image description here

Or this might be slightly clearer;

enter image description here

Is there a way of being able to (in one query) search through all the key/value pairs with a regex? The script will not know how many customField key/value pairs there are!

So far I have in PHP;

['poco.customFields.0.value' => ['$regex' => '.*'.$query.'.*', '$options' => 'i']],

Which is working on the first key/value pair nicely.. But not the others and I don't know how to do that without either doing two queries or just guessing that there will be no more than, say, 100 and just looping through it.

  • 写回答

1条回答 默认 最新

  • dongyu8694 2017-01-05 07:39
    关注

    Assuming you want to acquire documents with contents of customFields matching specific regex expression, there are two interpretations I can think of.

    (1) Return all documents with at least one value in customFields matching the pattern:

    [ 'customFields.value' => [ '$regex' => $pattern, '$options' => 'i' ]]
    

    (2) Return all document with all values in customFields matching the pattern:

    [ 'customFields.value' => [ '$not' => new MongoDB\BSON\Regex('\b^(?!'.$pattern.').+', 'i') ]]
    

    The first query is self-explanatory: iterate through all elements of customFields array and perform a regex check on each. If at least one of the elements matches the pattern, the parent document is returned.

    The second one is a bit more sophisticated. Requirement "where all elements match particular pattern" is equivalent to "where no single element does not match particular pattern". In order to achieve double negation, we use $not along with inverse regex expression created by applying negative lookahead to the same query we have used before. Since $not refuses to accept strings, we generate immediate regex expression by using an instance of MongoDB\BSON\Regex class.

    More information on negative lookahead may be found here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改