Extract field value from mongodb BasicDBobject - java

I am developing simple web application to learn jsp, mongodb, html. I have created an simple registration form in jsp which takes Name, Address and MobileNo information from user and insert it into mongodb, Now I want to retrieve this stored data and put value of every field in individual string variable.
Ex:
Name: varun; Address: Nagpur; MobileNo: 1234567890
Above data is stored in mongodb as:
{
"_id" : ObjectId("5259bacea6f8b1c4cd3431d3"),
"Name" : "varun",
"Address" : "nagpur",
"MobileNumber" : "1234567890"
}
Retrieved in jsp as follows:
MongoClient mongoC = new MongoClient(new ServerAddress("Localhost",27017));
DB database = mongoC.getDB("dbfrnzout");
DBCollection collec1 = database.getCollection("coll");
DBObject dock= collec1.findOne();
out.println(dock);
This code print one record as json document and I want to store value associated with every
field in individual string variable, something like this:
String s1 = varun ie. value of field Name
Need some guidance.

DBObject implements the Map<String, Object> interface so you should be able to do something like:
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
Be careful with the casts and make sure you are certain of the type and existence of each field. For numeric values I strongly recommend casting to a Number instead of Integer since MongoDB will re-cast values to a Long or Double at the weirdest times.
HTH, Rob.
Edit: If you are iterating over the results of a query you will have to inspect each document as it is returned from the iterator
DBCollection collec1 = database.getCollection("coll");
for( DBObject dock : collec1.find() ) {
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
// Do Something...
}

Do something like this to get an object from a cursor
while (cursor.hasNext())
dbObject o = cursor.next()

Related

String query validate on json data

Map<String, Object> data = new HashMap<>()
data.put("Description","laks");
data.put("EntityName","Pub");
data.put("Severity","Critical");
String query = "Severity = Critical AND (EntityName contains P OR
EntityName contains p )";
In the above sample code I want to apply/validate the "query" string on sample json object "data". Is there any sample code which can help me. In above sample data and query it should return false?
It looks like you need this library:
https://github.com/json-path/JsonPath

Get JSON tag with random name

I have this JSON:
{
"-1":{
"name":"Ad hoc",
"modifiedBy":"",
}
},
"9":{
"name":"my name",
"modifiedBy":"me",
}
}
}
The tags "-1" and "9" are IDs that I don't know.
I need get the tag "9" using the "name" "my name" with a JSON path.
How can I do that? I use Java.
I'm assuming the JSON in your question is in Java's JSONObject form. Let's call this object myjson. Let's also say you are trying to get the ID of the sub-object that has an internal "name" value of "Ad hoc":
String nameKey = "Ad hoc";
String theID = "";
Set keys = myjson.keySet();
Iterator iter = keys.iterator();
while(iter.hasNext()) {
String key = (String)iter.next();
String name = (String)jsonObject.getJSONObject(key).get("name");
if (name.equals(nameKey)) {
theID = key;
}
}
The variable theID should now contain the ID you want. If no match is found, theID will be an empty string.

Mongo Java Driver - How to update a subdocument into an array element

How could I update a specific field in subdocument of array element ?
My question is similar to the following below, but in my case I need to update just a subdocument value.
MongoDB: How do I update a single subelement in an array, referenced by the index within the array?
I have the following documento model :
{
_id : "xpto",
other_stuff ... ,
templates : [
{
templateId:"template-a"
body: {
en_US:"<p>Hello World!</p>"
}
},
{
templateId:"template-b"
body: {
es_ES:"<p>Holla !</p>"
}
}
]
}
So, In mongodb shell the following statement works perfectly for me:
db.apiClient.update({"_id":"xpto","templates.templateId":"template-b"}, {$set:{"templates.$.body.es_ES":"<h1>Gracias !</h1>"}})
However , when i try to do it with Mongo Java Driver , I get an IllegalArgumentException.
BasicDBObject selectQuery = new BasicDBObject("_id", "xpto");
selectQuery.put("templates.templateId", "template-b");
BasicDBObject updateQuery = new BasicDBObject();
for(String locale : template.getBody().keySet()) {
String updateBodyLocaleExpression = new StringBuilder()
.append("templates.$.body.").append(locale).toString();
String updateBodyLocaleValue = template.getBody().get(locale);
updateQuery.put(updateBodyLocaleExpression, updateBodyLocaleValue);
}
updateQuery.put("$set", updateQuery);
getCollection(COLLECTION_NAME).update(selectQuery, updateQuery, true, true);
It throws the following exception :
Caused by: java.lang.IllegalArgumentException: Invalid BSON field name templates.$.body.es_ES
at org.bson.AbstractBsonWriter.writeName(AbstractBsonWriter.java:494)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:127)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:61)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
at com.mongodb.connection.RequestMessage.addDocument(RequestMessage.java:253)
at com.mongodb.connection.RequestMessage.addCollectibleDocument(RequestMessage.java:219)
at com.mongodb.connection.UpdateMessage.encodeMessageBodyWithMetadata(UpdateMessage.java:77)
at com.mongodb.connection.RequestMessage.encodeWithMetadata(RequestMessage.java:160)
at com.mongodb.connection.WriteProtocol.execute(WriteProtocol.java:85)
Is something wrong with my code ?
Thanks.
Yes. You construct wrong updateQuery. You put fields templates.$.body... in the BasicDbObject and then add same document into $set field into itself. MongoDB tries to update field templates.$.body. and here $ is the part of the field name instead of operator.
Here is working example:
//List is for testing purposes only
List<String> locales = Arrays.asList("en_US", "en_UK");
Document query = new Document("_id", "xpto")
.append("templates.templateId", "template-b");
Document updateQuery = new Document();
for (String locale : locales) {
updateQuery.put("templates.$.body." + locale, "<pre>Updated " + locale + "</pre>");
}
collection.updateOne(query, new Document("$set", updateQuery));
Document is almost the same as BasicDbObject but more general.

Get ISO date object from mongoDb using Java

I want to get Iso date object value from mongodb collection.
below is my mongodb Collections
{
"_id" : ObjectId("55c4657f036499106cf73fae"),
"from" : "Administrator",
"subject" : " Exception details :: InternalSession",
"dateTs" : ISODate("2015-08-07T07:59:59.172Z")
}
i want to get dateTs column value i.e iSODate.
Below is my java code:
while (requestsCursor.hasNext()) {
DBObject dbObject = requestsCursor.next();
JSONArray toArr = new JSONArray();
String from = (String) (dbObject.containsField(FROM) ? dbObject.get(FROM) : "-");
ISO8601DateFormat dT = (ISO8601DateFormat) dbObject.get("dateTs");
System.out.println("dateTs : "+dT);
}
I am getting null value
please Suggest ..

MongoDB java driver get records where date between and user is

From a collection named "persons", I want to retreive all records where date is between
"14-11-2014" and "20-11-2014" <-- These are both in string format (dd-mm-yyyy)
AND
user: "Erik"
My mongoDB
{
"_id" : "546c9f26dbeaa7186ab042c4", <------this one should NOT be retreived
"Task: "Sometask" because of the user
"date" : "20-11-2014",
"user" : "Dean"
},
{
"_id" : "546caef6dbeaa7186ab042c5", <--------- This one should be retreived
"task": "A task",
"date" : "20-11-2014",
"user" : "Erik"
}
{
"_id" : "546caef6dbeaa7186ab042c5", <----- This one should NOT be retreived
"task": "A task", because of the date
"date" : "13-11-2014",
"user" : "Erik"
}
I am using java mongo java driver 2.11.3
Maybe there is some solution using BasicDBObject?
I'm very curious.. thanks
EDIT
I'm using:
public static String findTimelines(String begin, String end, String username) throws UnknownHostException, JSONException{
DBCollection dbCollection = checkConnection("timelines");
BasicDBObject query = new BasicDBObject();
query.put("date", BasicDBObjectBuilder.start("$gte", begin).add("$lte",end).get());
query.put("user", username);
dbCollection.find(query).sort(new BasicDBObject("date", -1));
DBCursor cursor = dbCollection.find(query);
return JSON.serialize(cursor);
}
Does work until you query something like "28-11-2014" to "01-12-2014", It doesn't return anything even though there is a object with date: "30-11-2014". I think this is because of the month change.
Also that object is retreived when you do: "28-11-2014" to "30-11-2014" because of the month staying the same
Please help!
Try something like this
BasicDBObject query = new BasicDBObject();
query.put("date", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
collection.find(query).sort(new BasicDBObject("date", -1));
This is the query you would use:
db.posts.find({date: {$gte: start, $lt: end}, user: 'Erik'});
You should first parse your date using SimpleDateFormat or alike to get a Date object.
Then put together your query using BasicDBObject:
BasicDBObject q = new BasicDBObject();
q.append("date", new BasicDBObject().append("$gte", start).append("$lt", end));
q.append("user", "Erik");
collection.find(q);

Categories