使用MongoDB查找文档,该数组包含一个字符串,该字符串是特定单词的子字符串 [英] Find documents, which array contains a string that is a substring to specific word, using MongoDB

查看:510
本文介绍了使用MongoDB查找文档,该数组包含一个字符串,该字符串是特定单词的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个收藏夹:

{"str": ["pho", "goa"], ...},
{"str": ["sma", "aba"], ...},
{"str": ["gag"], ...}
...

我想选择所有文档,其中的字段(此处为str)包含一个字符串,该字符串是某个单词的子字符串.例如smartphone.因此,查询结果应为:

And I want to select all the documents, which field (str here) contains a string, which is a substring to some word. smartphone for example. So the result of the query should be:

{"str": ["pho", "goa"], ...},
{"str": ["sma", "aba"], ...}

我该怎么做?

此问题与

This question is related to #54279248, where you don't have to search within array.

推荐答案

您可以使用以下聚合:

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $anyElementTrue: {
                    $map: {
                        input: "$str",
                        as: "s",
                        in: { $ne: [ -1, { $indexOfBytes: [ "smartphone", "$$s" ] } ] }
                    }
                }
            }
        }
    }
])

想法是您可以利用 $ indexOfBytes 检查"smartphone"中包含的str中的字符串,然后只需要使用

The idea is that you can take advantage of $indexOfBytes to check string from str is contained in "smartphone" and then you just need to use $anyElementTrue to check if condition is met for any item from str

Mongo游乐场此处

这篇关于使用MongoDB查找文档,该数组包含一个字符串,该字符串是特定单词的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆