简体   繁体   中英

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.

Example if i search CZ1001, i will get back Obj 1 EmailAddress details.

If i search CE1001, i will get back Obj 2 and Obj 3 EmailAddress details.

The object id are uniquely created when i inserted records at the start if that helps.

I am able to get the objects on MongoDB Shell using

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", String_variable) is allowed

For a particular Interest , your mongoDB query would look like(taking CE1001 as an example):

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.

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")
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM