I am quite new to MongoDb. i use a find and get the result in JSON format.
{"Name": "Harshil", "Age":20}
so what i need is parse this in java and get values in the variables.
String name should contain Harshil
int age should contain 20
is there a way to store these details in JAVA object?
Here is how to connect to the your MongoDB:
MongoClient client = new MongoClient("localhost",27017); //with default server and port adress
DB db = client.getDB( "your_db_name" );
DBCollection collection = db.getCollection("Your_Collection_Name");
After the connecting you can pull your data from the server.Below, i assume that your document has Name and Age field :
DBObject dbo = collection.findOne();
String name = dbo.get("Name");
int age = dbo.get("Age");
Take a look at GSON library. It converts JSON to Java objects and vice-versa.
There are many ways and tools, one of which is gson
class Person {
private String name;
private int age;
public Person() {
// no-args constructor
}
}
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
And I'd feel lax if I didn't add this link too.
You can just do it with the Java driver :
DBObject dbo = ...
String s = dbo.getString("Name")
int i = dbo.getInt("Age")
Using another framework on top of the Java driver should be considered I you have multiple objects to manage.
As we don't want to use the deprecated methods so, you can use the following code to do so:
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("your_db_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
FindIterable<Document> iterDoc = collection.find();
MongoCursor<Document> dbc = iterDoc.iterator();
while(dbc.hasNext()){
try {
JsonParser jsonParser = new JsonFactory().createParser(dbc.next().toJson());
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(jsonParser, Person.class);
String name = person.get("Name");
String age = person.get("Age");
} catch (Exception e){
e.printStackTrace();
}
JsonFactory, JsonParser,etc. are being used from Jackson to de-serialize the Document to the related Entity object.
Have you considere Morphia?
#Entity
class Person{
#Property("Name") Date name;
#Property("Age") Date age;
}
I would prefer using the new Mongodb Java API. It's very clean and clear.
public MyEntity findMyEntityById(long entityId) {
List<Bson> queryFilters = new ArrayList<>();
queryFilters.add(Filters.eq("_id", entityId));
Bson searchFilter = Filters.and(queryFilters);
List<Bson> returnFilters = new ArrayList<>();
returnFilters.add(Filters.eq("name", 1));
Bson returnFilter = Filters.and(returnFilters);
Document doc = getMongoCollection().find(searchFilter).projection(returnFilter).first();
JsonParser jsonParser = new JsonFactory().createParser(doc.toJson());
ObjectMapper mapper = new ObjectMapper();
MyEntity myEntity = mapper.readValue(jsonParser, MyEntity.class);
return myEntity;
}
Details at
http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-fetch-operation-using-java-api.html
Newer Way [Since getDB() is Deprecated]
Since the original answer was posted the DBObject and corresponding method client.getDB have been deprecated. For anyone who may be looking for a solution since the new update I have done my best to translate.
MongoClient client = new MongoClient("localhost",27017); //Location by Default
MongoDatabase database = client.getDatabase("YOUR_DATABASE_NAME");
MongoCollection<Document> collection = database.getCollection("YOUR_COLLECTION_NAME");
Once connected to the document there are numerous familiar methods of getting data as a Java Object. Assuming you plan to have multiple documents that contain a persons name and their age I suggest collecting all the documents (which you can visualize as rows containing a name and age) in an ArrayList then you can simply pick through the documents in the ArrayList to convert them to java objects as so:
List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>());
for (Document document : documents) {
Document person = documents.get(document);
String name = person.get("Name");
String age = person.get("Age");
}
Honestly the for loop is not a pretty way of doing it but I wanted to help the community struggling with deprecation.
Try Using this function to convert JSON returned by mongodb to your custom java object list.
MongoClient mongodb = new MongoClient("localhost", 27017);
DB db = mongodb.getDB("customData-database");
DBCursor customDataCollection = db.getCollection("customDataList").find();
List<CustomJavaObject> myCustomDataList = null; // this list will hold your custom data
JSON json = new JSON();
ObjectMapper objectMapper = new ObjectMapper();
try {
//this is where deserialiazation(conversion) takes place
myCustomDataList = objectMapper.readValue(json.serialize(customDataCollection),
new TypeReference<List<Restaurant>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
CustomJavaObject:
public class CustomJavaObject{
//your json fields go here
String field1, field2;
int num;
ArrayList<String> attributes;
//....write relevantgetter and setter methods
}
sample json:
{
"field1": "Hsr Layout",
"field2": "www.google.com",
"num": 20,
"attributes": [
"Benagaluru",
"Residential"
]
},
{
"field1": "BTM Layout",
"field2": "www.youtube.com",
"num": 10,
"attributes": [
"Bangalore",
"Industrial"
]
}
Related
I wrote query in MongoDB which retrieved two columns, one for id and the other is array. I have tried to read the array using Java but I cannot.
try {
Bson filter = eq("_id", "1260718680159199238");
Bson project = eq("Tweets.Text", 1L);
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
"mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass%20Isolated%20Edition&ssl=false"
)
);
MongoDatabase database = mongoClient.getDatabase("Amazon-tweets");
MongoCollection<Document> collection = database.getCollection("tweets");
FindIterable<Document> result = collection.find(filter).projection(project);
for (Document doc : result) {
String s = doc.getString("Tweets.1");
System.out.println("orig " + s);
}
}//END try
catch (Exception e) {
}//
You can't use the dot notation to retrieve values like that post query.
Depending on the driver version you're using you can use either of these solutions:
(I'm assuming each tweet is a separate document here, but same should apply if it's something different)
List<Document> tweets = (List<Document>) doc.get("Tweets");
List<Document> tweets = doc.getList("Tweets", Document.class); // since 3.10
tweets.forEach(...
You can find the documentation here: https://mongodb.github.io/mongo-java-driver/
I have one Model Object. In which, i have multiple values. I want to store this Values in SQLite. But data is large, so i want to store Direct Model object
in databse. So i convert model Object to string and store it into database.
Now, Problem is that how to convert this String value to Model Object.
If you have any idea, please share that with Me.
For example,
Person p = new Person();
p.setname("xyz");
p.setage("18");`
String person=p.toString();
Now How to get this "person" string back to Person "p" model object.
This is my code.
ContentValues values = new ContentValues();
String favorite_id = UUID.randomUUID().toString();
values.put(EMuseumLocalData.KEY_FAVORITE_EXHIBITS_ID, favorite_id);
values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_ID, Integer.parseInt(categoryByCustomerList.get(position).getSubCategoryItemID()));
try {
Gson gson = new Gson();
String personString = gson.toJson(getAllCategory.get(position).toString());
values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_DATA, personString);
Gson gson1 = new Gson();
CategoryByCustomer categoryByCustomer = gson1.fromJson(personString, categoryByCustomer.getName());
} catch (JSONException e) {
e.printStackTrace();
}
You should use GSON or similar libs for this.
Store to DB
For example If you use GSON
Person p = new Person();
p.setname("xyz");
p.setage("18");
Gson gson = new Gson();
String personString = gson.toJson(p);
Now store this personString to DB.
Read from DB
Get back this object from database, read string from DB and convert it to object like below
String personStringFromDB = READ_LOGIC_OF_DB;
Gson gson = new Gson();
Person p = gson.fromJson(personStringFromDB, Person.class);
For more information, read GSON - Gson Example
Consider using a json string representation of the Model Object. There are many java libraries like Jackson, Gson etc., available to help you with serialization/deserialization part.
Here's a sample code to do this in Jackson
//For conversion of Person object(person) to json String:
String personJsonString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(person);
//For conversion of json String back to Person object(person)
Person person = new com.fasterxml.jackson.databind.ObjectMapper().readValue(personJsonString, Person.class);
You can make Model Object serializable. You need to store the serialized object in SQLite. When you need it, you just get that serialized object from SOLite and deserialize it.
BasicDBObject whereQuery = new BasicDBObject();
DBCollection coll = db.getCollection("mycollection"); whereQuery.put("employee", "bonus");
DBCursor cursor =coll.find(whereQuery);
cursor.pretty();
context i am not able to do cursor.pretty() as method is not associated with DBCursor
I am printing data using
while(cursor.hasNext())
{
out.println(cursor.next(););
out.println("</br>");
}
please give me a way for pretty printing in servlets
As far as I know the pretty function is only available in the mongo shell. You will have to write a function yourself.
i couldn't find pretty in DBCursor.By using the tutorial based on Google Gson i found a work around which is mentioned below
Document myDoc = collection.find().first();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myDoc);
System.out.println(json);
which will be printed like below and i have mongodb java driver 3.2.1
{
"_id": {
"$oid" : "50906d7fa3c412bb040eb577"
},
"student_id": 0,
"type": "exam",
"score": 54.6535436362647
}
the below code may
DBObject myObj = cursor.hasNext();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myObj);
out.println(json);
out.println("<br>");
while (cursorDoc.hasNext()) {
System.out.println("Printning value of cursor " +cursorDoc.next());
if(cursorDoc.hasNext()) {
DBObject o = cursorDoc.next();
String Name= (String) o.get("Name") ;
request.setAttribute("shopname",shopname);
RequestDispatcher dispatcher =request.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
I have a JSON array which contains objects such as this:
{
"bjones": {
"fname": "Betty",
"lname": "Jones",
"password": "ababab",
"level": "manager"
}
}
my User class has a username which would require the JSON object's key to be used. How would I get the key of my JSON object?
What I have now is getting everything and creating a new User object, but leaving the username null. Which is understandable because my JSON object does not contain a key/value pair for "username":"value".
Gson gson = new Gson();
JsonParser p = new JsonParser();
JsonReader file = new JsonReader(new FileReader(this.filename));
JsonObject result = p.parse(file).getAsJsonObject().getAsJsonObject("bjones");
User newUser = gson.fromJson(result, User.class);
// newUser.username = null
// newUser.fname = "Betty"
// newUser.lname = "Jones"
// newUser.password = "ababab"
// newUser.level = "manager"
edit:
I'm trying to insert "bjones" into newUser.username with Gson, sorry for the lack of clarification
Use entrySet to get the keys. Loop through the entries and create a User for every key.
JsonObject result = p.parse(file).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet();
for(Map.Entry<String, JsonElement> entry : entrySet) {
User newUser = gson.fromJson(p.getAsJsonObject(entry.getKey()), User.class);
newUser.username = entry.getKey();
//code...
}
Using keySet() directly excludes the necessity in iteration:
ArrayList<String> objectKeys =
new ArrayList<String>(
myJsonObject.keySet());
Your JSON is fairly simple, so even the manual sort of methods (like creating maps of strings etc for type) will work fine.
For complex JSONs(where there are many nested complex objects and lists of other complex objects inside your JSON), you can create POJO for your JSON with some tool like http://www.jsonschema2pojo.org/
And then just :
final Gson gson = new Gson();
final MyJsonModel obj = gson.fromJson(response, MyJsonModel.class);
// Just access your stuff in object. Example
System.out.println(obj.getResponse().getResults().get(0).getId());
I am trying to update a document using as criteria the Mongo ObjectId which I store in a parallel field contentGroupId but it is not working.
What is the best practice for updating a document in Mongo using the Java Driver when you are using the internal id as the primary key?
#Override
public void updateContentGroup( ContentGroup contentGroup ) {
DBCollection contentGroupCollection = db.getCollection( "contentGroups" );
Gson gson = new Gson();
String json = gson.toJson( contentGroup );
DBObject contentGroupDoc = (DBObject) JSON.parse( json );
BasicDBObject criteriaObject = new BasicDBObject();
criteriaObject.append( "_id", "ObjectId(\"520a56b730047339c26ec1fa\")");
contentGroupCollection.update( criteriaObject, contentGroupDoc );
}
Thanks-in-advance,
Guido
I think your problem is here:
criteriaObject.append( "_id", "ObjectId(\"520a56b730047339c26ec1fa\")");
Should be:
criteriaObject.append( "_id", new ObjectId("520a56b730047339c26ec1fa");
That way the field value is treated as an object id, not as string (containing the literal "ObjectId")