Search code examples
javamongodbmorphia

In MongoDb Morphia how to delete or replace an array object


I can only find how to remove first, last or selected object
but i need to delete the entire array.

In Morphia i have this below Document FriendList.

In the Document you see the array friendList.
I need to update this array with new "friends".

What need to happen is i must delete all entries in the friendList
before populating it with new friends.

Was thinking i could delete it and then simply insert a new
array friendList containing "friends".

How can i delete the array?

Maybe im all wrong about how to do this since i cannot find a solution..

@Entity
public class FriendList {

    @Id private ObjectId id;

    public Date lastAccessedDate;

    @Indexed(name="uuid", unique=true,dropDups=true)  
    private String uuid;


    List<String> friendList;

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public List<String> getFriendList() {
        return friendList;
    }

    public void insertFriend(String friend) {
        this.friendList.add(friend);
    }

}

from the documentation I try this in various combinations with no luck:

mongo.createUpdateOperations(FriendList.class).removeAll("friendList", "??");

Solution

  • You can use the unset method, and then addAll or just use set:

    http://code.google.com/p/morphia/wiki/Updating#set/unset

    Should look something like this:

    ops = datastore.createUpdateOperations(FriendList.class).unset("friendList");
    datastore.update(updateQuery, ops);
    ops = datastore.createUpdateOperations(FriendList.class).addAll("friendList", listOfFriends);
    datastore.update(updateQuery, ops);
    

    or with set:

    ops = datastore.createUpdateOperations(FriendList.class).set("friendList", listOfFriends);
    datastore.update(updateQuery, ops);