如何使用spring数据mongo将序列化对象保存到mongodb

时间:2017-11-08 09:00:58

标签: serialization spring-data-mongodb

我有如下弹簧数据mongo POJO。这里Map动态地具有键值对。

@Document(collection = "sample_event")
public class SampleEvent {

    private static final long serialVersionUID = 3575974453648692913L;

    @Id
    private ObjectId id;

    @Field("unique_id")
    private String uniqueId;

    @Field("ts")
    private Date timestamp;

    private Map<String, Object> fields = new HashMap<String, Object>();

    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
        this.id = id;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public void setUniqueId(String uniqueId) {
        this.uniqueId = uniqueId;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public void setFields(Map<String, Object> obj) {
         fields = obj;
    }

    public Map<String, Object> getFields() {
        return fields;
    }
}

我想用上面的POJO将json数据保存到mongo(这里abc,xyz,lmn将从'fields Map'获得):

{
    "_id" : ObjectId("5a02c169e68c0a19248fe023"),
    "unique_id" : "111111",
    "ts" : ISODate("2017-10-10T18:30:05.000Z"),
    "abc" : "info",
    "xyz" : "notice",
    "lmn" : "25"
}

但它保存如下:

{
        "_id" : ObjectId("5a02c169e68c0a19248fe023"),
        "unique_id" : "111111",
        "ts" : ISODate("2017-10-10T18:30:05.000Z"),
        "fields" : 
               { 
                   "abc" : "info",
                   "xyz" : "notice",
                   "lmn" : "25" 
               }
  }

如何在保存到mongo时从嵌套的json中删除'fileds'属性。请帮帮我。

0 个答案:

没有答案