سؤال

For this document structure:

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

How can I perform a $elemMatch Mongo shell query from Casbah?

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

I tried this from the Casbah code's test directory, but I got 0 results.

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

I'm getting a type mismatch on the collection.find(builder) line.

EDIT Provided more text for compile-time error.

[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

Full gist - https://gist.github.com/kman007us/6817354

هل كانت مفيدة؟

المحلول

Theres a little extra wrapping there thats not needed like the builder - heres a cleaned up example:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top