如何使用MongoDB Scala驱动程序将聚合结果累积到集合中

时间:2018-03-21 03:11:05

标签: mongodb scala

我正在将我自己用Java编写的代码迁移到Scala,后者在MongoDB中进行聚合。但是我被困在如何使用MongoDB Scala Driver在集合中累积聚合结果。

Java代码:

mongoCollection.aggregate(aggregatePipeline)
    .map(document -> {
      Document group = document.get("_id", Document.class);
      return new Document("chat", group).append("count", document.get("count"));
    })
    .into(new ArrayList<>(), (results, e) -> {
      Document document = new Document("chats", results);
      System.out.println(document.toJson());
    });

Scala代码:

mongoCollection.aggregate(aggregatePipeline)
    .map[Document](doc => Document("chat" -> doc.get("_id"), "count" -> doc.get("count")))
    .subscribe((doc: Document) => println(doc.toJson))

从Scala中的代码中可以看出,我没有累积聚合结果,因为我不知道如何从Java代码中的.into()方法获得相同的行为,使用MongoDB Scala驱动程序。我在互联网上做了很多研究,但没有成功。如果有人可以帮助我,我很感激。

2 个答案:

答案 0 :(得分:0)

您应该特别使用隐式Observable helpers collect()。还有一个toFuture()方法可以有效地运行收集并将结果作为Future返回。

mongoCollection.aggregate(aggregatePipeline)
    .map[Document](doc => Document("chat" -> doc.get("_id"), "count" -> doc.get("count")))
    .collect()
    .subscribe((docs: Seq[Document]) => println(docs))

答案 1 :(得分:0)

您可以设置Seq [Document]类型的变量,然后在订阅事件触发后将结果文档序列附加到该变量。使用Promise / Future等待结果。例如:

def find_all (collection_name: String): Seq[Document] = {

    /* The application will need to wait for the find operation thread to complete in order to process the returned value. */

    log.debug(s"Starting database find_all operation thread")

    /* Set up new client connection, database, and collection */
    val _client: MongoClient = MongoClient(config_client)
    val _database: MongoDatabase = _client.getDatabase(config_database)
    val collection: MongoCollection[Document] = _database.getCollection(collection_name)

    /* Set up result sequence */
    var result_seq : Seq[Document] = Seq.empty

    /* Set up Promise container to wait for the database operation to complete */
    val promise = Promise[Boolean]

    /* Start insert operation thread; once the thread has finished, read resulting documents. */
    collection.find().collect().subscribe((results: Seq[Document]) => {
      log.trace(s"Found operation thread completed")
      /* Append found documents to the results */
      result_seq = result_seq ++ results
      log.trace(s" Result sequence: $result_seq")

     /* set Promise container */      
     promise.success(true)

     /* close client connection to avoid memory leaks */
      _client.close
     })

    /* Promise completion result */
    val future = promise.future

    /* wait for the promise completion result */
    Await.result(future, Duration.Inf)
    /* Return document sequence */
    result_seq

  }