在字符串中的子字符串(单词)中搜索,该字符串位于 mongodb 中文档的子字段

时间:2021-07-25 17:38:04

标签: mongodb

我想提取所有的文档,其中任何子字段(dialogue.text)中的文档都有某个词。

我的示例文档是这样的

{
    "_id": {
        "$oid": "60fd992366a307a689b58987"
    },
    "id": "1objOZYLF5fdz3WykWo",
    "name": "bbb.mp4",
    "dialogue": [{
        "type": "cue",
        "data": {
            "start": 2378,
            "end": 3211,
            "text": "[ footsteps approaching ]"
        }
    }, {
        "type": "cue",
        "data": {
            "start": 3295,
            "end": 4587,
            "text": "morty, you got to come on."
        }
    }, {
        "type": "cue",
        "data": {
            "start": 4672,
            "end": 6130,
            "text": "you got to come with me."
        }
    }, {
        "type": "cue",
        "data": {
            "start": 6215,
            "end": 7048,
            "text": "what's going on?"
        }
    }, {
        "type": "cue",
        "data": {
            "start": 7132,
            "end": 8049,
            "text": "i got a surprise for you, morty."
        }
    }]
}

例如,我如何提取任何对话.文本字段中的所有文档都带有“惊喜”一词。

假设我为对话字段创建了索引,我该如何使用“$text”来查找文档

如果有任何关于制作更好、更高效的文档的建议,也非常感谢。

我是否应该使用基于 SQL 的数据库来加快查询速度?

谢谢。

2 个答案:

答案 0 :(得分:0)

更好的方法是使用 Text search

<块引用>

MongoDB 提供了一种很好的技术,即文本搜索。使用这个 我们可以从文本中找到一段文本或一个指定的词 字符串字段。或者换句话说,MongoDB 允许您执行 查询操作从字符串中查找指定的文本。在 MongoDB,我们可以使用文本索引和 $text 执行文本搜索 操作员

如果你需要正则表达式查找,你可以做

<EditText 
    android:inputType="textMultiLine"/>

工作Mongo playground

答案 1 :(得分:0)

首先,使用它来制作文本字段的索引。如果你不运行这个,你就不能在字段中搜索文本:

  db
      .collection.yourCollection
      .createIndex({ "dialogue.data.text": "text" });

制作索引后,您可以搜索:

   db
      .collection.yourCollection
      .find({ $text: { $search: "your word" } })
      .toArray();