2

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

Marty
  • 534
  • 8
  • 24

1 Answers1

2

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

cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • I won't always have Hello world in the input string, there may be different words and different amounts – Marty Jun 08 '23 at 06:32
  • @Marty what do u mean can give an example – cmgchess Jun 08 '23 at 06:40
  • Imagine input in html and script that listen input change and sends entered string to a server. On a server I receive string and I don't know what in that string. What can I do with unknown string to use regex `word1.*word2...wordN`, there can be N words in the input string? – Marty Jun 08 '23 at 06:47
  • You can build the regex dynamically in your code before you call the query – nimrod serok Jun 08 '23 at 06:48
  • @Marty are you referring to something like this `"word1 word2 word3".replace(/ /g,".*")` or `"word1 word2 word3".split(" ").join(".*")`. not sure what the string you get looks like – cmgchess Jun 08 '23 at 06:52
  • 1
    yep. early morning affects the absence of the brain :-D I can split the string. Thanks :) – Marty Jun 08 '23 at 07:10