-->

当ReactiveMongo已经存在的MongoDB更新文档(MongoDB update a do

2019-10-21 04:47发布

我正在写使用的MongoDB数据库和ReactiveMongo作为驱动Scala的Web应用程序。

我有一个集合命名recommendation.correlation中,我保存了产品和类别之间的相关性。

文档具有以下形式:

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

现在我正在写的方法如下:

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}
  }

问题是,该方法插入复制文件。 为什么出现这种情况?

我已经使用解决db.recommendation.correlation.ensureIndex({"category": 1, "attribute": 1}, {"unique": true, "dropDups":true })但我怎么能解决了这一问题,而不使用索引?

怎么了??

Answer 1:

你想要做什么是就地更新。 要做到这一点与ReactiveMongo您需要使用更新操作来告诉它哪些字段更新,以及如何。 相反,你已经通过correlation (我以为是某种BSONDocument),以集合的更新方法。 简单地要求更换新的文件,如果唯一索引值是不同将导致添加到收藏一个新文件。 而不是传递的correlation ,你应该传递使用的一个BSONDocument 更新运营商 ,如$设置(设置字段)或$增量(由一个递增的数字字段)。 关于这样做的详细信息,请参阅MongoDB的文档,修改文档



文章来源: MongoDB update a document when exists already with ReactiveMongo