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.

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

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接