【问题标题】:How to query "contains" using MongoDB Java 3?如何使用 MongoDB Java 3 查询“包含”?
【发布时间】:2017-10-25 08:33:37
【问题描述】:

我正在使用 Java 驱动程序 3 来处理 MongoDB。 我的集合中有以下文档。

  {
    "_id" : ObjectId("59231945aefa1a301db180a1"),
    "username" : "off",
    "trx_type" : "pair",
    "amount" : 100000,
    "note" : "testpair 2:2"
  },
  {
    "_id" : ObjectId("591d7a0b03c09b5142fb5602"),
    "amount" : 100000,
    "trx_type" : "pair",
    "note" : "2:2",
    "username" : "ok"
  }

我要查询这两条记录。

如果我使用这个,从命令行: db.transactions.find("note": /2:2/) 包含以下文档。

{
    "_id" : ObjectId("5925e6a8aefa1a339a8c013f"),
    "username" : "oktrade001",
    "trx_type" : "pairing bonus",
    "time" : NumberLong("1495656104204"),
    "amount" : 100000,
    "note" : "22:22"
}

尝试了几件事:

这仅返回精确的“2:2”,不包含: Document transaction = transactions.find(eq("note", s + ":" + s)).first();

这不起作用: String note = "/" + s + ":" + s + "/"; Document transaction = transactions.find(eq("note", note)).first();

阅读有关 $regex 的信息,找不到用于 Mongo Java 3 的示例查询。

请帮助...谢谢您。

更新: 所以...这是我需要在 Java 驱动程序中执行的 mongo 命令: db.transactions.find({"note": {"$regex": /2:2$/}}).pretty() 在 mongo 命令行中尝试了这个,得到了我想要的。如何在 Java 驱动程序 3+ 中编写这个? 还有...我需要将数字 2 更改为变量

【问题讨论】:

  • 试试db.transactions.find({"note": {"$regex": /2:2/}})
  • 试试Document transaction = transactions.find(regex("note", note)).first();
  • @WiktorStribiżew 感谢您的回复,我需要 java 驱动程序命令。请参考我上面的更新
  • @Veeram 这不起作用,请参考我上面的更新...
  • 试试这样:transactions.find(regex("note", ".*" + Pattern.quote(s) + ":" + Pattern.quote(s) + ".*"));。如果您需要在字符串的最后找到值。删除最后一个+ ".*"

标签: java regex mongodb


【解决方案1】:

您需要考虑到正则表达式模式是默认锚定的,因此需要整个字符串匹配

知道了,你就可以轻松控制比赛的位置了:

  • 字符串开头:

    transactions.find(regex("note", Pattern.quote(s) + ".*"));

  • 字符串结束:

    transactions.find(regex("note", ".*" + Pattern.quote(s)));

  • 字符串中的任意位置:

    transactions.find(regex("note", ".*" + Pattern.quote(s) + ".*"));

注意:如果您需要在包含换行符的字符串中查找匹配项:transactions.find(regex("note", "(?s).*" + Pattern.quote(s) + ".*"));,或者像这样:transactions.find(regex("note", "(?s).*" + Pattern.quote(s) + ".*", "s"));,则需要一个 DOTALL 修饰符(它的内联版本是 (?s))。请参阅regex method docs。支持的修饰符列表(在 MongoDB 中称为 options)可以是 checked here

【讨论】:

  • 我的“s”不是一个字符串,而是一个整数。 Pattern.quote 还能用吗?
  • 不,您需要将 int 转换为带有 Integer.toString(s) 的字符串。
【解决方案2】:

这就是我们所做的:

Document transaction = transactions.find(and(regex("note", ".* " + s + ":" + s + " .*"), eq("username", username))).first();

刚刚添加了用户名验证条件

【讨论】:

    【解决方案3】:

    我相信,使用正则表达式的正确方法:

    transactions.find(regex("note", "^2:2.*"));

    如果表达式可能包含特殊符号,请不要忘记转义:

    transactions.find(regex("note", "^" + Pattern.quote("my * expression") + ".*"));

    【讨论】:

    • 感谢您的回复,但您的回答正好返回“2:2”。我需要的是 2:2,所以我也会得到“testpair 2:2”
    • 在这种情况下你需要 regex("note", ".*2:2.*")
    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 2011-08-02
    • 2015-01-10
    • 2016-02-29
    • 2014-11-24
    • 1970-01-01
    • 2022-01-18
    • 2012-05-24
    相关资源
    最近更新 更多