I'm using Java driver 3 to work with MongoDB. I have the following documents in a collection.
{
"_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"
}
I want to query for this two records.
From command line if I use this: db.transactions.find("note": /2:2/) The following document is included.
{
"_id" : ObjectId("5925e6a8aefa1a339a8c013f"),
"username" : "oktrade001",
"trx_type" : "pairing bonus",
"time" : NumberLong("1495656104204"),
"amount" : 100000,
"note" : "22:22"
}
Tried several things:
This only return exact "2:2", not contains:
Document transaction = transactions.find(eq("note", s + ":" + s)).first();
This doesn't work:
String note = "/" + s + ":" + s + "/";
Document transaction = transactions.find(eq("note", note)).first();
Read about $regex, couldn't find example queries using this for Mongo Java 3.
Kindly help... Thank you before.
update:
so... this is the mongo command I need to do in Java driver:
db.transactions.find({"note": {"$regex": /2:2$/}}).pretty()
tried this in mongo command line, at got what I wanted. how to write this in Java driver 3+?
also... i need to change number 2 to a variable
db.transactions.find({"note": {"$regex": /2:2/}})Document transaction = transactions.find(regex("note", note)).first();transactions.find(regex("note", ".*" + Pattern.quote(s) + ":" + Pattern.quote(s) + ".*"));. If you need to find the value at the very end of the string. remove the last+ ".*".