【问题标题】:Initialize to MongoCursor初始化为 MongoCursor
【发布时间】:2015-09-24 14:02:20
【问题描述】:

我需要一个var(以下为res)来接受find() 的答案,即MongoCursor,因为我必须能够访问我在if-conditions 中的变量(见下文)。

这是我正在做的事情:

var query = new MongoDBObject()
val res = ""

if ("condition_1" == field_1))
{
    query += "field" -> "t"

    if ("condition_2" == "field_2"))
    {
        res = collection.find(q).sort("basic_field" -> 1)
       }
    else if ("condition_2" == "field_2"))
    {
        res = collection.find(q).sort("important_field" -> -1).limit(101)
    }
}

//Perform some operations on res

如何初始化我的res 以接受MongoCursor?

var res = MongoCursor 和 var res = DBCursor 不起作用。

【问题讨论】:

    标签: mongodb scala casbah


    【解决方案1】:
    var res: MongoCursor = _
    

    这会将默认值分配给 res(可能为 null)。

    但您应该尽可能避免使用 var。 因为在scala中如果可以返回结果,可以直接将结果赋值给res,例如:

    val res =  if ("condition_1" == field_1)) {
                 query += "field" -> "t"
                 if ("condition_2" == "field_2")) {
                   collection.find(q).sort("basic_field" -> 1)
                 } else if ("condition_2" == "field_2")) {
                   collection.find(q).sort("important_field" -> -1).limit(101)
                 }
               }
    

    【讨论】:

    • var res: MongoCursor = _ 不起作用,因为:local variables must be initialized。所以我使用了null,它成功了。一旦它正常工作,我会尝试你的建议。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2020-02-08
    相关资源
    最近更新 更多