如何使用Casbah在MongoDB上按对象ID查找?

时间:2011-04-07 01:25:31

标签: scala mongodb casbah

我正在尝试编写一个查询,通过Casbah按对象ID查找,这似乎微不足道但是...我找不到。

我试过了:

def get(id: Option[String]): User = { 
    val mongoDB : MongoDB = MongoConnection().apply("test")
    val mongoColl : MongoCollection = mongoDB.apply("users")
    val objectId = id.getOrElse().asInstanceOf[String]
    val o : DBObject = MongoDBObject("_id" -> objectId)
    val u = mongoColl.findOne(o)
    val user = new User()
    for(x <- u){
         user.id = x.getAs[String]("_id")
         user.username = x.getAs[String]("username")
         user.password = x.getAs[String]("password")
    }
    user
}

和此:

def get(id: Option[String]): User = { 
        val mongoDB : MongoDB = MongoConnection().apply("test")
        val mongoColl : MongoCollection = mongoDB.apply("users")
        val objectId = "ObjectId(\"" +id.getOrElse().asInstanceOf[String] + "\")"
        val o : DBObject = MongoDBObject("_id" -> objectId)
        val u = mongoColl.findOne(o)
        val user = new User()
        for(x <- u){
             user.id = x.getAs[String]("_id")
             user.username = x.getAs[String]("username")
             user.password = x.getAs[String]("password")
        }
        user
    }

这个编译运行但没有结果。 我也试过这个:

def get(id: Option[String]): User = { 
    val mongoDB : MongoDB = MongoConnection().apply("test")
    val mongoColl : MongoCollection = mongoDB.apply("users")
    val objectId : ObjectId = id.getOrElse().asInstanceOf[ObjectId]
    val o : DBObject = MongoDBObject("_id" -> objectId)
    val u = mongoColl.findOne(o)
    val user = new User()
    for(x <- u){
         user.id = x.getAs[String]("_id")
         user.username = x.getAs[String]("username")
         user.password = x.getAs[String]("password")
    }
    user
}

但是这个不能编译,因为String不能转换为ObjectId。

java.lang.ClassCastException: java.lang.String cannot be cast to org.bson.types.ObjectId

感谢您的帮助:)

1 个答案:

答案 0 :(得分:12)

“_ id”通常存储为MongoDB中的ObjectID而不是String ... String和ObjectID是不同的类型,您不能将String强制转换为ObjectId。 ObjectId也是MongoDB中的一个独特类型,因此ObjectId(“abcdefgh123”)与字符串“abcdefgh123”不同。

您需要在Casbah内搜索ObjectID。试试这个:

def get(id: Option[ObjectId]): User = { 
    val mongoDB : MongoDB = MongoConnection().apply("test")
    val mongoColl : MongoCollection = mongoDB.apply("users")
    val objectId : ObjectId = id.getOrElse().asInstanceOf[ObjectId]
    id.foreach( oid => {
      val o : DBObject = MongoDBObject("_id" -> oid)
      val u = mongoColl.findOne(o)
      val user = new User()
      for(x <- u){
        user.id = x.getAs[ObjectId]("_id")
        user.username = x.getAs[String]("username")
        user.password = x.getAs[String]("password")
      }
      user
    })
  }