Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a MongoDB document to a Java class

I'm using the MongoDB driver in Java.

Say I have a MongoDB document in the collection db.people:

{"name":"Joe", "surname":"Blow", "age":20}

and a Java class that looks something like

`public class Person {
   String name;
   String surname;
   int age;`

  `public void setPersonalInfo(String name, String surname, int age) {
     this.name = name;
     this.surname = surname;
     this.age = age;
   }
}`

How do I parse the information from my document into my class? Is there a way to do this by manipulating the document in the form of a BasicDBObject? I looked through the methods and couldn't make sense of how, as my first inclination was to use a method which returns an array of key value pairs (as far as I know, no such method exists).

like image 659
baxdab Avatar asked Mar 14 '26 14:03

baxdab


1 Answers

Jongo is your friend:

Person p = people.find("{age: {$gt: 18}}").as(Person.class)
like image 177
AlikElzin-kilaka Avatar answered Mar 17 '26 05:03

AlikElzin-kilaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!