【发布时间】: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) + ".*"));。如果您需要在字符串的最后找到值。删除最后一个+ ".*"。