Java 在MongoDb Morphia中,如何删除或替换数组对象

Java 在MongoDb Morphia中,如何删除或替换数组对象,java,mongodb,morphia,Java,Mongodb,Morphia,我只能找到如何删除第一个、最后一个或选定的对象 但是我需要删除整个数组 在Morphia中,我有以下文档好友列表 在文档中可以看到数组好友列表 我需要用新的“friends”更新此数组 需要做的是我必须删除好友列表中的所有条目 在用新朋友填充它之前 我想我可以删除它,然后简单地插入一个新的 数组好友列表包含“好友” 如何删除数组 也许我对怎么做完全错了,因为我找不到解决办法 @Entity public class FriendList { @Id private ObjectId i

我只能找到如何删除第一个、最后一个或选定的对象
但是我需要删除整个数组

在Morphia中,我有以下
文档
好友列表

文档中
可以看到
数组
好友列表

我需要用新的
“friends”
更新此
数组

需要做的是我必须删除
好友列表中的所有条目

在用新朋友填充它之前

我想我可以删除它,然后简单地插入一个新的
数组
好友列表
包含
“好友”

如何删除
数组

也许我对怎么做完全错了,因为我找不到解决办法

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

}

一般来说,您只需要使用常规(Java)列表操作—所以要清除它,请将列表设置为null,根据需要删除或添加条目,。。。因此,您可以非常轻松地加载、操作并持久化实体

为什么您甚至有
mongo.createUpdateOperations(FriendList.class)
?如果一个对象相当大,您可能不希望加载和持久化整个内容来更新单个字段。然而,我将从简单的方法开始,如果需要,只使用更复杂的查询

不要过早地优化-根据需要构建、基准测试和优化

编辑:

在您的实体中:

public function clearFriends(){
    this.friendList = null;
}
无论您在哪里需要它:

FriendList friendList = ...
friendList.clearFriends();
persistence.persist(friendList); // Assuming you have some kind of persistence service with a persist() method

或者您可以使用一些特殊的Morphia方法,如unset,但这可能是一种过度使用…

您可以使用unset方法,然后添加全部或仅使用set:

应该是这样的:

ops = datastore.createUpdateOperations(FriendList.class).unset("friendList");
datastore.update(updateQuery, ops);
ops = datastore.createUpdateOperations(FriendList.class).addAll("friendList", listOfFriends);
datastore.update(updateQuery, ops);
或与set一起:

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

我对这个有点陌生。如何使用Morphia将列表设置为null?如果createUpdateOperations不合适,我还可以使用其他什么。或者,如果你能告诉我在文档中的什么地方描述了这一点。只要弄清楚,我想在属性上使用“unset”命令。我在上面添加了一个简短的示例(注释对代码没有好处…),是的,你也可以再保存一次;更新方法将向服务器发送更少的数据,并减少其他更改(通过更新设置)在服务器上发生冲突的可能性,这可能不仅仅是一个优化…(如果您不更新-只是为了避免混淆)
ops = datastore.createUpdateOperations(FriendList.class).set("friendList", listOfFriends);
datastore.update(updateQuery, ops);