【问题标题】:Query MongoDB - Getting codec error whe querying distinct()查询 MongoDB - 查询 distinct() 时出现编解码器错误
【发布时间】:2020-04-07 10:47:25
【问题描述】:

我是 Scala 的 mongodb 新手。我正在尝试在我的记录中获取所有不同的 id,我应该得到 [id1,id2,id3,...,idn]

我的代码

val mongoClient: MongoClient = MongoClient()
val db: MongoDatabase = mongoClient.getDatabase("myDB")

val collection = db.getCollection("Datalake")
val response = Await.result(collection.distinct[Double]("idWell").toFuture(), Duration(5, TimeUnit.SECONDS))
if (response != null && response.nonEmpty) {
      response.foreach(println(_))
}

我在线程“main”org.bson.codecs.configuration.CodecConfigurationException 中遇到异常:找不到双倍的编解码器。我需要在数据库连接器中配置任何东西吗?该代码是否正确或者我应该使用理解来处理未来?无论哪种方式,我都会遇到同样的错误

输入数据应该是这样的(数组只是一个例子,记录是MongoDB中的文档):

[
  {
    "_id": "[field id]",
    "oilFieldId": "[the id I'm using which represents an oil field id]",
    "tef":"[a number]",
    "agg":"[the field I'd like to update (currently = '')]",
    "date": "[year-month-day]"
  },
  {
    "_id": "[another field id]",
    "oilFieldId": "[the id I'm using which represents an oil field id]",
    "tef":"[a number]",
    "agg":"[the field I'd like to update (currently = '')]",
    "date": "[year-month-day]"
  },
  {
    "_id": "[another field id]",
    "oilFieldId": "[the id I'm using which represents an oil field id]",
    "tef":"[a number]",
    "agg":"[the field I'd like to update (currently = '')]",
    "date": "[year-month-day]"
  },
  ...
]

输出应该是一个“oilFieldId”数组

[1232345, 135245, 123155, 24524, ...]

【问题讨论】:

  • 请在jsoneditoronline.org分享请求数据和输出数据
  • 好的,我确实进行了编辑,显示了输入和所需的输出。够清楚吗?谢谢

标签: mongodb scala distinct future codec


【解决方案1】:

发现错误。问题是返回值的编解码器,它实际上不是 Double,而是 BsonInt32.type。这就是为什么在 org.bson.codecs 中找不到编解码器

我已经完成了这项工作,并从 Future.onComplete 获得了价值。这是代码

val d = for(
      a <- collection.distinct[BsonInt32]("oilFieldId").toFuture()
    )yield a

    d.onComplete{
      case Success(element) => element.foreach{
        System.out.println(_)
      }
      case Failure(t) => System.out.println(t.getMessage)
    }

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2014-08-21
    • 2020-04-19
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多