Morphia如何忽略额外的字段/元素?

时间:2015-05-18 05:35:41

标签: java mongodb morphia

我是新手,当我使用morphia java mongodb时,我遇到了问题。 我有"新闻" mongodb中带有该集合的数据库是" article" 一篇示例文章:

{
   "_id": ObjectId("54b77156d52fbb115abbc7ed"),
   "title": "test title",
   "thumbnail": "http://test.com/images/2015/01/15/kt169333-1.jpg",
   "imgsLoc": "/home/test/public/images/2015/01/15/kt169333-1.jpg",
   "sapo": "SampleSapo",
   "author": null,
   "content": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
   "source": "http://example.com/news/test/1",
 ... [it has more about 30 fields after this line ...]
}

我的工作只需要获取内容并保存新文章的textLength字段。 这样说:

{
   "_id": ObjectId("54b77156d52fbb115abbc7ed"),
   "title": "test title",
   "thumbnail": "http://test.com/images/2015/01/15/kt169333-1.jpg",
   "imgsLoc": "/home/test/public/images/2015/01/15/kt169333-1.jpg",
   "sapo": "SampleSapo",
   "author": null,
   "content": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"textLength": NumberLong(441) <= new field
   "source": "http://example.com/news/test/1",
 ... [it has more about 30 fields after this line ...]
}

当我使用吗啡时 因为我只需要content来计算textlength,所以我不关心其他领域。 但是当我使用吗啡时。其他字段丢失,只有content和textLength字段保存在数据库中; 我要映射的文章类是:

public class Article {
@Id
protected ObjectId id;
protected String content;
protected long textLength;

// Getset method

}

为什么其他领域会丢失?

在没有数据丢失的情况下更新集合的最快方法是什么? 将此Article类映射到mongodb时如何忽略额外的字段?

感谢

1 个答案:

答案 0 :(得分:0)

即使您没有在代码中显示它,我也假设您正在使用文档中的保存。因此,您用您拥有的属性替换它,因此“缺少”字段。

如果您不想映射整个文档,则需要显式更新字段,而不是简单地调用save。请参阅Morphia documentation on updates