MongoDB update a document when exists already with ReactiveMongo

女生的网名这么多〃 提交于 2019-12-11 11:27:56

问题


I'm writing a Scala web application that use MongoDB as database and ReactiveMongo as driver.

I've a collection named recommendation.correlation in which I saved the correlation between a product and a category.

A document has the following form:

{ "_id" : ObjectId("544f76ea4b7f7e3f6e2db224"), "category" : "c1", "attribute" : "c3:p1", "value" : { "average" : 0, "weight" : 3 } }

Now I'm writing a method as following:

def calculateCorrelation: Future[Boolean] = {
    def calculate(category: String, tag: String, similarity: List[Similarity]): Future[(Double, Int)] = {
      println("Calculate correlation of " + category + " " + tag)  
      val value = similarity.foldLeft(0.0, 0)( (r, c) => if(c.tag1Name.split(":")(0) == category && c.tag2Name == tag) (r._1 + c.eq, r._2 + 1)  else r
            ) //fold the tags
      val sum = value._1 
      val count = value._2
      val result = if(count > 0) (sum/count, count) else (0.0, 0)
      Future{result}

    }

  play.Logger.debug("Start Correlation")
  Similarity.all.toList flatMap { tagsMatch =>
    val tuples = 
    for {
      i<- tagsMatch
    } yield (i.tag1Name.split(":")(0), i.tag2Name) // create e List[(String, String)] containing the category and productName
    val res = tuples map { el =>
      calculate(el._1, el._2, tagsMatch) flatMap { value =>
        val correlation = Correlation(el._1, el._2, value._1, value._2) // create the correlation
        val query = Json.obj("category" -> value._1, "attribute" -> value._2)
        Correlations.find(query).one flatMap(element => element match {
          case Some(x) => Correlations.update(query, correlation) flatMap {status => status match {
            case LastError(ok, _, _, _, _, _, _) => Future{true}
            case _ => Future{false}
          }

          }
          case None => Correlations.save(correlation) flatMap {status => status match {
            case LastError(ok, _, _, _, _, _, _) => Future{true}
            case _ => Future{false}
          }

          }
        }
            )

      }

    }

   val result = if(res.exists(_ equals false)) false else true
   Future{result}
  }

The problem is that the method insert duplicated documents. Why this happen??

I've solved using db.recommendation.correlation.ensureIndex({"category": 1, "attribute": 1}, {"unique": true, "dropDups":true }), but how can I fixed the problem without using indexes??

What's wrong??


回答1:


What you want to do is an in-place update. To do that with ReactiveMongo you need to use an update operator to tell it which fields to update, and how. Instead, you've passed correlation (which I assume is some sort of BSONDocument) to the collection's update method. That simply requests replacement of the document, which if the unique index value is different will cause a new document to be added to the collection. Instead of passing correlation you should pass a BSONDocument that uses one of the update operators such as $set (set a field) or $incr (increment a numeric field by one). For details on doing that, please see the MongoDB Documentation, Modify Document



来源:https://stackoverflow.com/questions/26606925/mongodb-update-a-document-when-exists-already-with-reactivemongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!