我是MongoDb和Morphia的新手 试图学习如何更新我的文档。
我无法从此页面看到/了解如何操作:
http://www.mongodb.org
我的文档如下所示:(这可能是一些错误)
@Entity
public class UserData {
private Date creationDate;
private Date lastUpdateDate;
@Id private ObjectId id;
public String status= "";
public String uUid= "";
public UserData() {
super();
this.statistic = new Statistic();
this.friendList = new FriendList();
}
@Embedded
private Statistic statistic;
@Embedded
private FriendList friendList;
@PrePersist
public void prePersist() {
this.creationDate = (creationDate == null) ? new Date() : creationDate;
this.lastUpdateDate = (lastUpdateDate == null) ? creationDate : new Date();
}
}
在该页面上,我看不到他们描述如何更新具有特定UserData
的{{1}}的任何地方
如uUid
update UserData.status
这是我认为我应该使用的:
uUid=123567
// morphia默认更新是更新所有UserData文档,以便如何更新选定的文档
ops=datastore.createUpdateOperations(UserData.class).update("uUid").if uuid=foo..something more here..
答案 0 :(得分:12)
我想这就是你想要的:
query = ds.createQuery(UserData.class).field("uUid").equal("1234");
ops = ds.createUpdateOperations(UserData.class).set("status", "active");
ds.update(query, ops);
答案 1 :(得分:2)
morphia界面有点笨拙且文档不清楚......但只更新单个特定文档的方法实际上已在the page Erik referenced 上演示:
// This query will be used in the samples to restrict the update operations to only the hotel we just created.
// If this was not supplied, by default the update() operates on all documents in the collection.
// We could use any field here but _id will be unique and mongodb by default puts an index on the _id field so this should be fast!
Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field("_id").equal(hotel.getId());
<强> ... 强>
// change the name of the hotel
ops = datastore.createUpdateOperations(Hotel.class).set("name", "Fairmont Chateau Laurier");
datastore.update(updateQuery, ops);
此外,a different documentation page显示了一种聪明的方法来隐藏实体类本身内的繁琐查询:
@Entity
class User
{
@Id private ObjectId id;
private long lastLogin;
//... other members
private Query<User> queryToFindMe()
{
return datastore.createQuery(User.class).field(Mapper.ID_KEY).equal(id);
}
public void loggedIn()
{
long now = System.currentTimeMillis();
UpdateOperations<User> ops = datastore.createUpdateOperations(User.class).set("lastLogin", now);
ds.update(queryToFindMe(), ops);
lastLogin = now;
}
}