How to find if a key exists in MongoDb document? - java

I have the following mongodb document
{
"user_100":{
"name": "Scott" ,
"uniqueDetails":{
"mobile":"9999999999",
"email": "scott#abc.com",
}
},
"user_101":{
"name": "Smith",
"uniqueDetails":{
"mobile":"9999999998",
"email": "smith#abc.com"
}
}
}
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.

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);

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

Related

Retrieve only the queried element in an object array in MongoDB using java

Suppose we have the following documents in a MongoDB collection:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
And the MongoDB query is
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
Can someone tell me how to write it in Java?
I am using:
List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));
BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);
DBCursor cursor = table.find(parameters1,obj2).limit(500);
and I am not getting anything.
The syntax of the Mongo Shell find function is:
db.collection.find(query, projection)
query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projection document Optional. Specifies the fields to return in the documents that match the query filter.
When translating this for execution by the Mongo Java driver you need to construct separate BasicDBObject instances for;
the query
the projection
Here's an example:
MongoCollection<Document> table = ...;
// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");
// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);
FindIterable<Document> documents = table
// assign the query
.find(query)
// assign the projection
.projection(projection);
System.out.println(documents.first().toJson());
Given the sample documents included in your question the above code will print out:
{
"shapes": [
{
"shape": "circle",
"color": "red"
}
]
}
This is identical to the output from db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});.

How to get specific value from sub-document in mongo

I want to find the specific field value from mongo sub-document, but its retrieving either full data or null value. I am using mongo 3.0.1 driver. Is there any issue with the syntax for the mongo specific driver.
Json data is:
{
"Demo": {
"Demo Data": {
"Building": {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
},
"Mode": "Building"
}
}
}
The code is as below:
DBCollection collection = db.getCollection("demo");
BasicDBObject field = new BasicDBObject();
BasicDBObject document = new BasicDBObject();
field1.put("_id", 0);
field1.put("Demo", 1);
DBCursor cursor = collection.find(document, field);
BasicDBObject object = new BasicDBObject();
BasicDBObject Mode = new BasicDBObject();
while (cursor.hasNext()) {
object = (BasicDBObject) cursor.next();
Mode.put("Mode", object.get(Mode));
System.out.println("Mode value is"+Mode);
}
but using above code, the output showing as:
Mode value is {"Mode":null}
The requirement is to get the following output:
{"Mode": "Building"}.
Please specify where the condition went wrong. Thanks for any help.
I think you are incorrectly assuming that since you have put field1.put("Demo", 1); , it would return you inner document, whereas no matter what it would always return you full document what it will do is omit other fields, but even then it would be full document which is right from the root.
while (cursor.hasNext()) {
object = (BasicDBObject) cursor.next();
Map map = object.toMap();
Mode.put("Mode", map.get("Demo").get("Demo Data").get("Mode")); //pre-check for NPE
System.out.println("Mode value is"+Mode);
}

How to Query MongoDB Using Child Nodes in Java

I'm trying to query mongodb with java. The name of my collection is: reads. Here is an example of a specific document I'm querying for:
{
"_id" : {
"d" : "B66929932",
"r" : "15500304",
"eT" : ISODate("2014-09-29T12:03:00Z")
},
"v" : 169000,
"iT" : ISODate("2015-04-10T20:42:07.577Z")
}
I'm trying to query where r = 15500304, eT = 2014-09-29T12:03:00Z and v = 169000. I'm able to do this in mongo pretty easily:
db.reads.find({ "_id.r" : "15500304", "_id.eT" : ISODate("2014-09-29T12:03:00Z"), "$where" : "this.v == 169000;"}).pretty()
I'm unable to figure out how to structure this in java. So far I've got:
DBCollection collection = db.getCollection("reads");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("_id.r", "15500304"));
obj.add(new BasicDBObject("_id.eT", "2014-09-29T12:03:00Z"));
obj.add(new BasicDBObject("v", 169000));
andQuery.put("$and", obj);
DBCursor cursor = collection.find(andQuery);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
My Question is: How do I query using these child nodes and return the matching document?
I'm unable to find any clear advice/examples online. Any and all advice is very appreciated.
You were close. Modify your query to:
DBCollection collection = db.getCollection("reads");
BasicDBObject query = new BasicDBObject();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInString = "2014-09-29T12:03:00Z";
Date date = df.parse(dateInString);
query.append("status.name", "Expired")
.append("_id.eT", date)
.append("v", 169000);
Or using QueryBuilder:
DBObject query = QueryBuilder.start()
.put("_id.r").is("15500304")
.put("_id.eT").is(date)
.put("v").is(169000)
.get();
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

How to convert mongo shell query to java basicDBObject?

I am having following mongo query which is executed in mongo shell.
db.test.update({
uuid: "160597270101684",
sessionId: "160597270101684.1"
}, {
$setOnInsert: {
stamps: {
currentVisit: "1377500985",
lastVisit: "1377500985"
}
},
$push:{
visits: {
page: "google.com",
method: "GET"
}
}
}, { upsert:true })
Because i am new to java, I am little bit confused to create the basicDBObject.
I had tried like this for sample
BasicDBObject doc = new BasicDBObject("uuid",1).append("session",2);
BasicDBObject upsertion = new BasicDBObject("upsert",true);
collection.update(doc,upsertion);
But its not working.
Any help will be great.
The upsert option isn't specified with a DBObject but with a third argument to DBCollection.update
public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi)
You'll need to form a DBObject for update by appending $setOnInsert, $push, stamps and visits.
BasicDBObject update = new BasicDBObject();
BasicDBObject stamps = new BasicDBObject();
stamps.append("currentVisit", "1377500985").append("lastVisit", "1377500985");
BasicDBObject visits = new BasicDBObject();
update.append("$setOnInsert", stamps).append("$push", visits);
collection.update(doc, update, true);

MongoDB $in with $and Query

Is this type of query possible?
I need to query the database for data for a specified date for a set of specified stocks. So the data needs to have "this" date and be one of "these" symbols.
I have the following code:
public void findDateStockSet(String date, ArrayList<String> symbolSet) throws UnknownHostException {
this.stocks = this.getCollectionFromDB();
BasicDBObject objectToFind = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("date", date));
obj.add(new BasicDBObject("symbol", new BasicDBObject("$in", symbolSet)));
objectToFind.put("$and", obj);
DBCursor cursor = this.stocks.find(objectToFind);
System.out.println("Finding Stocks");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println();
}
This always comes up null. Can someone explain how to make a query like this work?
You don't need to use $and operator, just build the query as the json below:
{ "date" : "20100223", "symbol" : { $in : [ "appl", "goog" ] } }
I like to use BasicDBObjectBuilder util class to build DBObjects. So your query will be:
DBObject query = BasicDBObjectBuilder.start()
.add("date", date)
.push("symbol")
.add("$in", symbolSet)
.get();

Categories

Resources