2011-10-10 58 views
6

Im完全新的MongoDb和Morphia和
试图学习如何更新我的文档。morphia和howto更新现有的文档字段

我不能看到/明白如何从这个页面做:
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具有特定的uUid
update UserData.status如果uUid=123567

这就是我想我应该用:

ops=datastore.createUpdateOperations(UserData.class).update("uUid").if uuid=foo..something more here.. 

//吗啡默认的更新是更新所有的UserData文档,如何更新选定

datastore.update(datastore.createQuery(UserData.class), ops); 

回答

7

我想这是你想要的:

query = ds.createQuery(UserData.class).field("uUid").equal("1234"); 
ops = ds.createUpdateOperations(UserData.class).set("status", "active"); 

ds.update(query, ops); 
+0

是的,为什么我不提及那个网页有这些信息。或者我错过了它,或者这不是解决集合内部文档的正常方式? – Erik

2

的吗啡界面有点笨拙和文档都不清楚......但更新Ô的方法NLY一个单一的,特定的文件实际上是表现出对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; 
    } 
} 
+0

我喜欢隐藏您显示的查询。我将如何调用'loggedIn()'方法?我确实需要为特定的“用户”权限创建查询?然后调用'loggedIn()'?我不需要拉出整个'User'对象,或者我可以缩短Java代码吗? – Erik

+0

@Erik:'loggedIn()'是'User'类的一个方便的方法。它假定您已经使用Mongo数据库中的文档填充了一个User对象。 还有其他方法可以检查,而不用拉出整个'User'对象。像User类的静态方法或在User * DAO *类中实现:http://code.google.com/p/morphia/wiki/DAOSupport – Leftium

相关问题