我在集合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字段包含单词Helloword的邮件.最重要的是,必须按照输入字符串的顺序找到单词,因此不能找到集合中的最后一个元素,但必须找到前两个元素.我知道如何通过匹配正则表达式来查找,但在第二种情况下,我不知道如何进行查找

推荐答案

您可以使用$regex和正则表达式this.com/r/8SbwHE/1" rel="nofollow noreferrer">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"
    }
  }
})
])

options: "i"表示不区分大小写.如果你不想要,就把它拿掉

playground

Node.js相关问答推荐

自动将Selify打开的Chrome窗口移动到Mac OS中的第三个显示器

如何在MongoDB中更新嵌套数组

如何在docker容器上正确安装nodejs?

如何使用 Node.js 连接到 Cloud SQL?

NodeJS `request` 库无法通过 multipart-form-data 将文件发布到 dotnet 服务器

Nodejs 从链接数组中获取数据并保存到 mongodb

express cors request.body formData显示undefined

加速 sequelize ORM 中的查询

Axios GET 返回不可读的响应

如何调用同名的两个函数?

aws cdk 2.0 init 应用程序无法构建更漂亮的问题,这来自 jest-snapshot

突然 React 无法执行create-react-app命令.为什么会发生这种情况,我该如何解决?

如果我使用像 express 这样的 node 服务器,是否需要 webpack-dev-server

用于排除多个文件的 node.js glob 模式

如何从 Redis 保存和检索会话

Node.js 17.0.1 Gatsby 错误-数字信封 routine ::不支持 ... ERR_OSSL_EVP_UNSUPPORTED

Route.get() 需要回调函数,但得到对象未定义

安装Node.js 安装n 安装Node.js?

Express js 阻止 GET /favicon.ico

Google Firebase 错误(函数返回未定义、预期的 Promise 或值)