MongoDB:按输入字符串或输入字符串中的单个单词进行匹配搜索。

huangapple go评论65阅读模式
英文:

MongoDB: search by match of the input string or single words from the input string

问题

我想要搜索包含 /Hello world/ig 或包含单词 Helloword 的消息,而且最重要的是 - 这些单词必须按输入字符串的顺序找到,所以集合中的最后一个元素不应该被找到,但前两个必须被找到。我知道如何使用正则表达式进行匹配,但在第二种情况下,我不明白该如何做。

英文:

I have field message in a collection messages, for example:

[
  {
   _id: "chrYMAqT8meXpqdrC",
   message: "Hello world. This is mongo"
  },
  {
   _id: "rKu5gf5zL6NaSvZ5Q",
   message: "Hello. This is mongo world"
  },
  {
   _id: "rKu5gf5zL6NaSvZ5Q",
   message: "world. This is mongo Hello"
  }
]

I want to search for messages where the message field contains /Hello world/ig or where the message field contains the words Hello and word. And most importantly - the words must be found in the order of the input string, so the last element in the collection must not be found, but the first two must. I know how to find by matching with regex, but in the second case i don't understand how to do it

答案1

得分: 2

你可以使用 $regex 与正则表达式 Hello.*world。也可以使用 这个

db.collection.find({
  message: {
    $regex: "Hello.*world",
    $options: "i"
  }
})

playground

或者你可以使用 $regexMatch

db.collection.find({
  $expr: {
    $regexMatch: {
      input: "$message",
      regex: "Hello.*world",
      options: "i"
    }
  }
})

options: "i" 表示大小写不敏感。如果不需要,可以移除它。

playground

英文:

you could use $regex with the regex Hello.*world. Also this

db.collection.find({
  message: {
    $regex: "Hello.*world",
    $options: "i"
  }
})

playground

or you could use $regexMatch

db.collection.find({
  $expr: {
    $regexMatch: {
      input: "$message",
      regex: "Hello.*world",
      options: "i"
    }
  }
})
])

options: "i" means case-insensitive. remove that if you don't want it

playground

huangapple
  • 本文由 发表于 2023年6月8日 14:05:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定