Edwin Langga
Edwin Langga

Reputation: 83

MongoDB ScalaDriver Query for nested array

I have been troubled by nested arrays in mongodb, and as soon as I have found a same question here in stackoverflow, I tried it out and worked on mongo shell. But now my problem is how to convert the said code to scala version using mongo scala driver. I would be delighted and happy for any ideas and answers.

Here is the test data. I will still use the same data as the one on the previous post.

db.multiArr.insert({"ID" : "fruit1","Keys" : [["apple", "carrot", "banana"]]})
db.multiArr.insert({"ID" : "fruit2","Keys" : [["apple", "orange", "banana"]]})


db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})
{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }

db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['banana']}}}})

{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }
{ "_id" : ObjectId("5065587e2aeb79b5f7374cc0"), "ID" : "fruit2", "Keys" : [ [ "apple", "orange", "banana" ] ] }

I know this will be a redundant post. But since the question was answered by 2012, I cannot see any hope of having any reply to my question if I post it there.

this is the link for the previous question: Querying an array of arrays in MongoDB

Thanks in advance.

Upvotes: 0

Views: 488

Answers (1)

sarveshseri
sarveshseri

Reputation: 13985

If you are using the mongo-scala-driver then,

import scala.collection.JavaConverters._
import org.mongodb.scala._

// if you have a connections string
val mongoClientSettings = MongoClientSettings.builder()
  .applyConnectionString("mongodb://localhost:27017")
  .build()

// if you have a cluster and ip's of the nodes
val servers = List("xx.xx.xx.xx", "xx.xx.xx.xx")
val serverAddresses = mongoConfig.servers.map(s => new ServerAddress(s)).asJava
val mongoClientSettings = MongoClientSettings.builder()
  .applyToClusterSettings(b => b.hosts(serverAddresses))
  .build()

val mongoClient = MongoClient(mongoClientSettings)

val mongoDatabase = mongoClient.getDatabase("your-database-name")

val mongoCollection = mongoDatabase.getCollection("multiArr")

val documentsFuture: Future[List[Document]] = mongoCollection.find(Document(
  "Keys" -> Document(
    "$elemMatch" -> Document(
      "$elemMatch" -> Document("$in" -> List("carrot"))
    )
  )
).toFuture

And now you have the future containing the list of your documents, I hope you can do the rest.

Upvotes: 1

Related Questions