Morphine and how to update an existing document field

Im brand new to MongoDb and Morphia and
trying to learn how to update my document.

I do not see / do not understand how to do this on this page:
http://www.mongodb.org

My document is as follows: (there might be some error here)

@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(); } } 

On this page I do not see the place where they describe how to update my UserData that has a specific uUid
Like update UserData.status if uUid=123567

Here is what I think I should use:

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

// Default update morphia - update the entire UserData document to update the selected ones.

 datastore.update(datastore.createQuery(UserData.class), ops); 
+6
source share
2 answers

I think this is what you want:

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

The morphine interface is a little clumsy, and the documents are not clear ... but the method of updating only one specific document is actually shown on the page that Erik links to :

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

In addition, another documentation page shows a smart way to hide this bulky request inside the entity class itself:

 @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; } } 
+2
source

Source: https://habr.com/ru/post/899003/


All Articles