Frage

Using Scala, MongoDB, Casbah.

Given a random list of strings:

  val names = {
    val listBuffer = new ListBuffer[String]
    for(n <- 1 to (new Random().nextInt(5) + 1)){
      val name = ((new Random().nextInt(26) + 65).asInstanceOf[Char]).toString
      listBuffer += name
    }
    listBuffer.toList
  }

Given a MongoDB document structure:

"_id": <uuid>  
"name": <string>  

How do I find all documents that have a name equal to an entry in my list using a single single MongoDBCollection.find() statement? (i.e using $or)

Thanks, - Don

War es hilfreich?

Lösung

MongoDB has conditional operator $in that lets test if a field's value is in a list of values (documentation)

collection.find({name: {$in: ["aaa", "bbb", "ccc"]}})

In Casbah this will look like

collection.find("name" $in names)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top