0

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?

1
  • 1
    What context are you using this in? If you're using Spring, Spring Data MongoDB will handle this for you magically. Commented Oct 22, 2013 at 6:52

9 Answers 9

6

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");
Sign up to request clarification or add additional context in comments.

1 Comment

You'll need to cast the results of the get, e.g. String name = (String)dbo.get("Name")
4

Take a look at GSON library. It converts JSON to Java objects and vice-versa.

Comments

3

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.

1 Comment

feel lax means?
1

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.

Comments

1

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.

Comments

0

Have you considere Morphia?

@Entity
class Person{
   @Property("Name") Date name;
   @Property("Age") Date age;
}

Comments

0

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.