2011-10-10 92 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

相關問題