mongodb-找到包含空格的值

发布于 2025-02-09 21:48:33 字数 235 浏览 1 评论 0原文

我有以下示例文档:

[
    { _id: "1", value: " 1" },
    { _id: "2", value: "2" },
    { _id: "3", value: "3 " }
]

如何运行mongodb 查找函数,该函数返回具有包含空间的值的文档?因此,在这种情况下,它将返回1,因为它在开始时有一个空间,而3个因为它的末端有一个空间。

I have the following sample documents:

[
    { _id: "1", value: " 1" },
    { _id: "2", value: "2" },
    { _id: "3", value: "3 " }
]

How can I run a MongoDB find function that returns the document(s) with a value that contains a space? So in this case, it would return 1 because it has a space at the beginning, and 3 because it has a space at the end.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东风软 2025-02-16 21:48:33

使用$ REGEX带有正则模式的操作员:

(^\s.+)|(.+\s$)

(^\ s。)whitespace(\ s)与至少一次发生的任何字符()匹配。

| - 或。

(。*\ s $) - group(()),匹配任何字符(),至少有一次出现(> +)在结尾处($)。

示例REGEX 101和测试数据


db.collection.find({
  value: {
    $regex: "(^\\s.+)|(.+\\s$)"
  }
})

样本mongo游乐场

Use $regex operator with regex pattern:

(^\s.+)|(.+\s$)

(^\s.*) - Group (()) with starts with (^) whitespace (\s) match any character (.) with at least one occurrence.

| - Or.

(.*\s$) - Group (()) with match any character (.) with at least one occurrence (+) at the end ($).

Sample Regex 101 and Test Data


db.collection.find({
  value: {
    $regex: "(^\\s.+)|(.+\\s$)"
  }
})

Sample Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文