سؤال

I have some code attempting to use $regex in a query:

val mongoClient = MongoClient()  // connect locally
val db = mongoClient("testdb")
val gridfs = GridFS(db)

val x = gridfs.files("filename" $regex "^[a-zA-Z]+\\/.+")
x.foreach(println)

The idea is to print all items in a directory. But when compiling it complains:

value $regex is not a member of String

But when I use $eq it seems to be fine:

val x = gridfs.files("filename" $eq "index.html")

A question was asked before that said:

It complains about $regex because it isn't finding a regex-able object on the right hand side to apply the conversion used to parse the $regex method--this is a problem you will run into with all of the following calls as well.

I am not sure if this is actually valid.

Further confusion lies $regex being defined in a trait without any implicit.

I am very new to Scala, the documentation is confusing at times.

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

المحلول

If you use the following query

("filename" -> "/name/i".r) or "filename" $regex "/name/i"

this will render

{ "name": { "$regex" : "/name/i" } } 

instead of

{ "name" : { "$regex" : /name/i } }

Casbah will recognize the type of the second argument and make the query appropriate. If you send pattern instead of regex like the following:

"filename" -> java.util.regex.Pattern.compile("name", Pattern.CASE_INSENSITIVE)

you will get what you want:

{ "filename" -> { "$regex" : "name", "$options" : "-i" } }

نصائح أخرى

You can use scala native regexes in your query eg:

val x = gridfs.files("filename" $eq "^[a-zA-Z]+\\/.+".r)

It seems that $regex for some reason wasn't added to the core DSL implicit converters and I'll fix that in Casbah 2.7 (SCALA-142)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top