1

对于此文档结构:

_id: 1, records : [{n : "Name", v: "Will"}]

如何$elemMatch从 Casbah 执行 Mongo shell 查询?

db.coll.find( {records : {$elemMatch : {n: : "Name", v : "Will"} } } )

我从 Casbah 代码的测试目录中尝试了这个,但我得到了 0 个结果。

var builder = MongoDBObject()
val elemMatch = "records" $elemMatch (MongoDBObject
                                      ("n" -> "Name", "v" -> "Will"))
builder = builder ++ elemMatch
collection.find(builder)

collection.find(builder)在线上遇到类型不匹配。

编辑为编译时错误提供了更多文本。

[error]  found   : collection.CursorType
[error]     (which expands to)  com.mongodb.casbah.MongoCursor
[error]  required: Int
[error]         collection.find(MongoDBObject(), elemMatch)
[error]                        ^
[error] one error found

完整要点 - https://gist.github.com/kman007us/6817354

4

1 回答 1

2

那里有一些额外的包装,不需要像builder- 这是一个清理过的例子:

import com.mongodb.casbah.Imports._
val coll = MongoClient()("test")("testB")
coll.drop()

coll += MongoDBObject("records" -> List(MongoDBObject("n" -> "Name", "v" -> "Will"), 
                                        MongoDBObject("n" -> "age", "v" -> 100)))

val elemMatch = "records" $elemMatch MongoDBObject("n" -> "Name", "v" -> "Will")
coll.find(elemMatch).count
于 2013-10-04T08:17:23.717 回答