Mongodb 初始化为MongoCursor
我需要一个Mongodb 初始化为MongoCursor,mongodb,scala,casbah,Mongodb,Scala,Casbah,我需要一个var(res在下面)来接受find()的答案,即MongoCursor,因为我必须在if条件下访问我的var(见下文) 以下是我正在做的: var query = new MongoDBObject() val res = "" if ("condition_1" == field_1)) { query += "field" -> "t" if ("condition_2" == "field_2")) { res = collec
var
(res
在下面)来接受find()
的答案,即MongoCursor
,因为我必须在if
条件下访问我的var(见下文)
以下是我正在做的:
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
不起作用
var res: MongoCursor = _
这会将默认值指定给res(可能为null)
但您应该尽可能避免使用var。
因为在scala中,if可以返回结果,所以可以直接将结果分配给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=.
无法工作,因为:必须初始化局部变量
。因此,我使用了null
,它起了作用。一旦它能正常工作,我会试试你的建议。非常感谢。