Search code examples
javamongodbmorphia

How to update a field in an entire collection in mongodb using morphia


I have a collection named TeamInfo, I created a class for it in java using morphia's annotations as follows:

@Entity("TeamInfo ")
public class TeamInfo {
    @Id
    private Integer teamInfoId;
    private String teamName;
    private Integer userCount;
}

I need to do an update operation on TeamInfo which changes the userCount and sets it to 0. I need a query which will set the userCount value in all the TeamInfo documents. So how to get all the TeamInfo documents in the query?

UpdateOperations<TeamInfo> updateOperation = datastore.createUpdateOperations(TeamInfo.class).set("userCount", 0);        
Query<TeamInfo> query = datastore. ??? ;
datastore.update(query, updateOperation);

I just started learning morphia, it will be great if someone can help me.


Solution

  • You use empty query without any condition.

    UpdateOperations<TeamInfo> updateOperation = datastore.createUpdateOperations(TeamInfo.class).set("userCount", 0);        
    Query<TeamInfo> query = datastore.createQuery(getEntityClazz()); // empty query
    datastore.update(query, updateOperation);