2014-10-28 3 views
1

데이터베이스로 MongoDB를 사용하고 ReactiveMongo를 드라이버로 사용하는 스칼라 웹 응용 프로그램을 작성하고 있습니다.MongoDB ReactiveMongo가 이미있을 때 문서 업데이트

제품과 카테고리 간의 상관 관계를 저장 한 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 })을 사용하여 해결했지만 인덱스를 사용하지 않고 어떻게 문제를 해결할 수 있습니까 ??

무엇이 잘못 되었습니까 ??

답변

2

적절한 업데이트가 필요합니다. ReactiveMongo를 사용하려면 업데이트 할 필드와 방법을 알려주기 위해 update operator을 사용해야합니다. 대신, 당신은(어떤 종류의 BSONDocument라고 가정 함)을 컬렉션의 업데이트 메소드에 전달했습니다. 이는 단순히 고유 인덱스 값이 다른 경우 문서에 대한 대체를 요청하기 만하면 컬렉션에 새 문서가 추가됩니다. correlation을 전달하는 대신 $ set (필드 설정) 또는 $ incr (숫자 필드를 하나씩 증가)와 같은 update operators 중 하나를 사용하는 BSONDocument를 전달해야합니다. 이를 수행하는 방법에 대한 자세한 내용은 MongoDB Documentation, Modify Document

을 참조하십시오.