使用Scala从MongoDB获取_id

时间:2013-10-31 12:46:03

标签: json mongodb scala

对于给定的JSON,如何让_id将其用作插入另一个JSON的id?

尝试获取如下所示的ID,但未返回正确的结果。

private def getModelRunId(): List[String] = {
  val resultsCursor: List[DBObject] =
    modelRunResultsCollection.find(MongoDBObject.empty, MongoDBObject(FIELD_ID -> 1)).toList
  println("resultsCursor >>>>>>>>>>>>>>>>>> " +  resultsCursor)
  resultsCursor.map(x => (Json.parse(x.toString()) \ FIELD_ID).asOpt[String]).flatten
}
{
"_id": ObjectId("5269723bd516ec3a69f3639e"),
"modelRunId": ObjectId("5269723ad516ec3a69f3639d"),
"results": [
{
  "ClaimId": "526971f5b5b8b9148404623a",
  "pricingResult": {
    "TxId": 0,
    "ClaimId": "Large_Batch_1",
    "Errors": [

    ],
    "Disposition": [
      {
        "GroupId": 1,
        "PriceAmt": 20,
        "Status": "Priced Successfully",
        "ReasonCode": 0,
        "Reason": "RmbModel(PAM_DC_1):ProgramNode(Validation CPG):ServiceGroupNode(Medical Services):RmbTerm(RT)",
        "PricingMethodologyId": 2,
        "Lines": [
          {
            "Id": 1
          }
        ]
      }
    ]
  }
},

2 个答案:

答案 0 :(得分:3)

如果你想找到objectId:

import com.mongodb.casbah.Imports._ 
collection.find(MongoDBObject(/*query*/)).map(_._id)

如果您想按ID进行查询:

collection.findOneByID(/*id*/)

答案 1 :(得分:2)

我想你使用的是Scala的官方驱动程序Casbah。

您只需要修改地图功能:

resultsCursor.map { x => x.as[org.bson.types.ObjectId](FIELD_ID)}

Casbah从BSON到Scala对象的反序列化,所以你不必自己做!