node.js - MongoDB:通过输入字符串或输入字符串中的单个单词的匹配进行搜索

标签 node.js mongodb

我在集合messages中有字段message,例如:

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

我想要搜索 message 字段包含 /Hello world/igmessage 字段包含单词 的消息>你好单词。最重要的是 - 必须按照输入字符串的顺序找到单词,因此不得找到集合中的最后一个元素,但必须找到前两个元素。我知道如何通过与正则表达式匹配来查找,但在第二种情况下我不明白该怎么做

最佳答案

您可以将 $regex 与正则表达式 Hello.*world 一起使用。另外this

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

playground

或者你可以使用$regexMatch

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

选项:“i”表示不区分大小写。如果您不需要,请将其删除

playground

关于node.js - MongoDB:通过输入字符串或输入字符串中的单个单词的匹配进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76429017/

相关文章:

spring - 如何在 YML 文件 spring boot 中配置 SSL mongodb 连接?

javascript - 如何根据数组中的值删除对象?

javascript - 等待每个循环

mysql - sequelize.js TIMESTAMP 不是 DATETIME

node.js - 使用 Request 的请求函数时,Github API 以 403 响应

java - 如何在 Spring Boot 应用程序中以 JSONObject 形式访问 MongoDB 文档

node.js - 如何使用 --experimental-modules 标志运行永久 js

node.js - MERN 教程问题 : Cannot read properties of undefined (reading 'collection' )

linux - 尽管尝试了来自 Stackoverflow 的不同修复程序,但 crontab 仍无法正常工作

c# - 使用 C# 驱动程序从 mongodb 集合中选择所有 _id