使用 jongo 将 JAVA 对象映射到 MongoDB 文档

Mapping a JAVA object with a MongoDB document using jongo

你好我有以下格式的合集

{
    "_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"
}

我已经制作了 3 个非常简单的 类 来映射对象。餐厅、地址和等级。 他们有以下格式 餐厅

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

地址

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

年级

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

我已经将最简单的代码编写到 toString() 一个映射对象,看看我得到了什么

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);

这段代码输出

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

我似乎无法修复我得到的邮政编码和 restaurant_id.

的空值

有人请帮助。谢谢。

您的字段名称与文档名称不匹配,因此不会被映射。如果我没记错的话,您可以使用 @JsonProperty 将那些 java 字段名称映射到您要从 mongodb.

中取回的文档名称