[英]MongoDB query for value in field with regex using Java
I am trying to query from my collection of documents which looks like: 我正在尝试从我的文档集合中查询:
{ "_id" : ObjectId("94"), "EmailAddress" :"adam@gmail.com","Interests": "CZ1001,CE2004" }
{ "_id" : ObjectId("44"), "EmailAddress" :"ben@gmail.com", "Interests":"CE1001,CE4002" }
{ "_id" : ObjectId("54"), "EmailAddress" :"chris@gmail.com","Interests":"CE1001,CE2002" }
An example is that i want to retrieve the email addresses, given that the field "Interests" has that value i am looking for. 一个示例是,由于字段“ Interests”具有我要查找的值,因此我想检索电子邮件地址。
Example if i search CZ1001, i will get back Obj 1 EmailAddress details. 例如,如果我搜索CZ1001,我将获得Obj 1 EmailAddress详细信息。
If i search CE1001, i will get back Obj 2 and Obj 3 EmailAddress details. 如果我搜索CE1001,我将获得Obj 2和Obj 3 EmailAddress的详细信息。
The object id are uniquely created when i inserted records at the start if that helps. 如果有帮助,当我在开始时插入记录时,对象ID是唯一创建的。
I am able to get the objects on MongoDB Shell using 我可以使用以下方法在MongoDB Shell上获取对象
db.users.find(Module: {"$regex": "CE1001"}})
Only the email addresses are needed. 只需要电子邮件地址。
I am trying to get all the email addresses and got stuck at this code. 我试图获取所有电子邮件地址,并被卡在此代码中。
Document doc = (Document) collection.find(new BasicDBObject("Module", {"$regex":"CE1001"})) .projection(Projections.fields(Projections.include("EmailAddress"), Projections.excludeId())).first();
Where new BasicDBObject("Module", {"$regex":"CE1001"})
is not allowed. new BasicDBObject("Module", {"$regex":"CE1001"})
。
new BasicDBObject("Module", String_variable)
is allowed 允许使用
new BasicDBObject("Module", String_variable)
For a particular Interest
, your mongoDB query would look like(taking CE1001 as an example): 对于特定的
Interest
,您的mongoDB查询看起来像(以CE1001为例):
db.collection.find({
$or: [
{
Interests: {
$regex: "^CE1001,"
}
},
{
Interests: {
$regex: ",CE1001,"
}
},
{
Interests: {
$regex: ",CE1001$"
}
}
]
},
{
"EmailAddress": 1
})
For others who happens to drop by this post. 对于碰巧不喜欢此帖子的其他人。 Below are the working codes.
以下是工作代码。 Credits to @Veeram.
致谢@Veeram。
FindIterable <Document> results = collection.find(new BasicDBObject("Module", new BasicDBObject("$regex", "CE1001")) .projection(Projections.fields(Projections.include("EmailAddress"), Projections.excludeId()));
for(Document doc : results) {
doc.getString("EmailAddress")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.