How to query a Array[String] for a regexp match?

2.4k views Asked by At

i try to query MongoDB via Casbah for a field that is a array of strings with a regexp.

For example:

I have a Maschine with a list of ips, that are stored as string in the fields ips. Now i want to search for all machines that have the subnet 192.168.

For me i looks like that the i cannot query an array with a regexp applied to every entry and if one of the entries matches the machine is returned.

Any way to make such a query ?

-- Fixed

Thanks for your help.

Everything works now. At the end i need to work around one limitation of Casbah, because i needed to join to queries with $or and Casbah complains about missing implicits with the regexp.

My final code for a RegExp Array query with an additional other field is:

val regexp = ".*" + parameter + ".*"
val nameQ = MongoDBObject("serverName" -> regexp.r)
val ipsQ = MongoDBObject("ips" -> regexp.r)
val bldr = MongoDBList.newBuilder
bldr += ipsQ
bldr += nameQ
val query = MongoDBObject("$or" -> bldr.result.asDBObject)
val result = find(query)

It is not the nicest code and the string concatenation of the parameter needs to be fixed. But it works :)

2

There are 2 answers

0
mnemosyn On BEST ANSWER

You can ignore the fact that this is an array:

> db.rx.insert( { "ips" : ["192.168.1.231", "192.168.2.231", "120.32.42.51"] });
> db.rx.find( { ips : /192./ } )
{ "_id" : ObjectId("4f104f0183bfca7a48b60da1"), 
  "ips" : [ "192.168.1.231", "192.168.2.231", "120.32.42.51" ] }

MongoDB always behaves like this: if you treat an array just like a normal field, it will apply the operation to each member and, if one matches, consider the parent document a match.

1
maerics On

See if the $elemMatch query operator will work for you.