如何使用Java删除MongoDB上的特定字段?

时间:2018-09-19 07:39:11

标签: java json mongodb jackson

我想在显示JSON中隐藏id_jadwal。但是现在id_jadwal继续显示在我的JSON上,我想在显示JSON中隐藏id_jadwal。我在框架和Jackson上使用MongoDB和Java jx-rs

[
    {
        "name": "Style",
        "startTimestamp": 1507611720,
        "endTimestamp": null,
        "place": "gh",
        "description": "gh",
        "status": "DONE",
        "creator": {
            "name": "Pulan",
            "email": "sd@gmail.com",
            "photo": "https://lh6.googleusercontent.com/-Q5Tx0bdvkAU/AAAAAAAAAAI/AAAAAAAAEyU/83rb_x1tyXA/photo.jpg"
        },
        "invitedUsers": [
            {
                "name": "Petra",
                "email": "sd.class@gmail.com",
                "photo": "",
                "present": false,
                "nearby": false
            }
        ],
        "id_jadwal": null,
        "_id": "59db02e8212cba197b7e9d2c"
    }

}]

我的代码:

BasicDBObject query = new BasicDBObject();
query.put("creator.email", email);
query.put("status", status.toString());
MongoCursor<Document> cursor = collection.find(query).iterator();
ObjectMapper objectMapper = new ObjectMapper();

while (cursor.hasNext()) {
    String jsonUser = cursor.next().toJson();

    Event event = objectMapper.readValue(jsonUser, Event.class);
    //objectMapper.setVisibility(event.getId_jadwal(), Visibility.NONE);

    events.add(event);
    events.remove("id_jadwal");

}

1 个答案:

答案 0 :(得分:1)

您必须使用Projection明确在请求级别排除字段:

MongoCursor<Document> cursor = collection.find(query).projection(Projections.exclude("id_jadwal").iterator();