JavaTechnical
JavaTechnical

Reputation: 9357

How to find if a key exists in MongoDb document?

I have the following mongodb document

{

"user_100":{
    "name": "Scott" ,
    "uniqueDetails":{
    "mobile":"9999999999",
    "email": "[email protected]",
    }
},
"user_101":{
    "name": "Smith",
    "uniqueDetails":{
    "mobile":"9999999998",
    "email": "[email protected]"
    }
}
}

Now, when a new user signs up, I would like to check if a given mobile number/email already exists. Is there any solution for this with Java MongoDB API.

Upvotes: 2

Views: 2330

Answers (2)

Piyush Khera
Piyush Khera

Reputation: 527

You can use the com.mongodb.QueryBuilder class to build a query:

DBObject query = QueryBuilder.start("mobile").is(mobileNumberToSearch)
    .or(QueryBuilder.start("email").is(emailToSearch).get()).get();

DBCursor dbCursor = collection.find(query);
if(dbCursor.hasNext()){
    System.out.println("mobile number or email already exists");
}

Upvotes: 0

jjmartinez
jjmartinez

Reputation: 807

You can do a query and search in the collection for the tags that you want:

For example:

BasicDBObject query = new BasicDBObject("email", email_to_seach);

DBCursor cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

Also, you can look for only the first document that has the email or mobile phone that you want, with:

BasicDBObject query = new BasicDBObject("email", email_to_seach);
DBObject myDoc = coll.findOne(query);

Upvotes: 1

Related Questions