MongoDB - 尝试替换数组中的值

时间:2016-12-06 15:11:13

标签: java mongodb morphia

Datastore ds = datastore;
Query<Document> query = ds.createQuery(Document.class).field("_id").equal(documentId);
UpdateOperations<Document> ops = ds.createUpdateOperations(Document.class).set("draft.languages", draft);
        ds.update(query, ops);

这是我正在尝试改变的课程

@Embedded("language")
   private String language;
   private String body;
之前的json:

                "languages" : [
                    {
                            "language" : "en",
                            "body" : "bla blaaaaaaaaaaaa ttttttt"
                    },
                    {
                            "language" : "ru",
                            "body" : "faksdfsdghfhshsssssssssh"
                    }
            ]

json之后:

                "languages" : [
                    {
                            "language" : "en",
                            "body" : "bla blaaaaaaaaaaaa ttttttt"
                    },
                    {
                            "language" : "ru",
                            "body" : "faksdfsdghfhshsssssssssh"
                    },
                    {
                            "language" : "en",
                            "body" : "blablablablalblalaakfslkdfjkldf"
                    }
            ]

草稿是语言列表

如果草案存在于segmant中,或者插入新的语言,我正在尝试更新,问题是主体不同,所以它总是插入新的而不是替换旧的。 我想我错过了一些东西(我使用$ addtoset并添加了列表而不是替换)

现在我正在使用set并替换整个列表,还有更好的选择吗?

感谢您的帮助!

我正在尝试做的例子

之前的json

插入

                    "languages" : [
                    {
                            "language" : "en",
                            "body" : "bla blaaaaaaaaaaaa"
                    },
                    {
                            "language" : "it",
                            "body" : "faksdfsdghfhshsssssssssh"
                    }
            ]

我希望结果如下:

                    "languages" : [
                    {
                            "language" : "en",
                            "body" : "bla blaaaaaaaaaaaa"
                    },
                    {
                            "language" : "ru",
                            "body" : "faksdfsdghfhshsssssssssh"
                    },
                    {
                            "language" : "it",
                            "body" : "faksdfsdghfhshsssssssssh"
                    }
            ]

1 个答案:

答案 0 :(得分:-1)

您可以为languages.language创建唯一索引,然后首先尝试更新它,如果没有匹配的文档,则将新文档推送到数组

long matchedCount = coll.updateOne(
  Filters.and(
    Filters.eq("_id", new ObjectId("yourid")), 
    Filters.eq("languages.language", "en")
  ), 
  new Document(
    "$set", 
    new Document("languages.$.body", "zuzuzu"))
  ).getMatchedCount();

if (matchedCount == 0) {            
  coll.updateOne(
    Filters.eq("_id", new ObjectId("yourid")),
    new Document(
      "$push", 
      new Document(
        "languages", 
        new Document("language", "en").append("body", "zuzuzu")
      )
    )
  );
}