9

我对 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在该页面上,我看不到他们描述如何更新具有特定uUid
Like update UserData.statusif的任何地方uUid=123567

这是我认为我应该使用的:

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

// morphia 默认更新是更新所有的 UserData 文档,所以如何更新选中的文档

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

2 回答 2

13

我想这就是你想要的:

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

ds.update(query, ops);
于 2011-10-10T22:10:06.517 回答
2

morphia 界面有点笨拙,文档也不清楚……但实际上在Erik 引用的页面上演示了一种仅更新单个特定文档的方法

// 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);

此外,另一个文档页面显示了一种巧妙的方法,可以将繁琐的查询隐藏在实体类本身中:

@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;
   }
}
于 2011-11-11T05:33:13.703 回答