javamappingmongodb-javajongo

Mapping a JAVA object with a MongoDB document using jongo


Hi I have a collection of the following format

{
    "_id" : ObjectId("572eb5df1d739cc73c21f953"),
    "address" : {
            "building" : "469",
            "coord" : [
                    -73.961704,
                    40.662942
            ],
            "street" : "Flatbush Avenue",
            "zipcode" : "11225"
    },
    "borough" : "Brooklyn",
    "cuisine" : "Hamburgers",
    "grades" : [
            {
                    "date" : ISODate("2014-12-30T00:00:00Z"),
                    "grade" : "A",
                    "score" : 8
            },
            {
                    "date" : ISODate("2014-07-01T00:00:00Z"),
                    "grade" : "B",
                    "score" : 23
            },
            {
                    "date" : ISODate("2013-04-30T00:00:00Z"),
                    "grade" : "A",
                    "score" : 12
            },
            {
                    "date" : ISODate("2012-05-08T00:00:00Z"),
                    "grade" : "A",
                    "score" : 12
            }
    ],
    "name" : "Wendy'S",
    "restaurant_id" : "30112340"
}

i have made 3 very simple classes to map objects. Restaurants, Address and Grade. they have the following format Restaurant

public String _id;
public Address address;
public String town;
public String cuisine;
public String name;
public String r_id;
public Grade [] grades;

Address

public int building;
public String street;
public long zip;
public float [] coord;

Grade

public String date;
public char grade;
public int score;

I have written the simplest of codes to just toString() a mapped object and see what i get

DB db = new MongoClient().getDB("test");
Jongo j = new Jongo(db);
MongoCollection collection = j.getCollection("restaurants");
Restaurant r1 = collection.findOne().as(Restaurant.class);
System.out.println(r1);

This code outputs

Restaurant: 572eb5df1d739cc73c21f953 / Wendy'S
Cuisine: Hamburgers
Restaurant ID: null
Address: 469 Flatbush Avenue 0, null
Grades: Tue Dec 30 05:00:00 PKT 2014 A / 8
Grades: Tue Jul 01 05:00:00 PKT 2014 B / 23
Grades: Tue Apr 30 05:00:00 PKT 2013 A / 12
Grades: Tue May 08 05:00:00 PKT 2012 A / 12

I cannot seem to fix the null I am getting for the zipcode and the restaurant_id.

Someone please help. Thanks.


Solution

  • Your field names don't match the documents names so they're not getting mapped over. If I recall correctly, you can use @JsonProperty to map those java field names to the document names you're getting back out of mongodb.