mongodbscalacasbah

Query Deep Nested MongoDB Object with Casbah [Scala]


{'_id': ObjectId('589df735be9fa2077dc5bb2e'),
 'name': 'train.2',
 'samples': [{'processed': {'eulerAngles': [1.946705159018607,
                                            -0.01405100477972897,
                                            0.02015610032297892]},
              'raw': {'accel': [0.01548936311155558,
                                0.0002011665492318571,
                                0.02126962691545486],
                      'gyro': [0.06626824289560318,
                               0.1328225582838058,
                               0.001385239884257317]},
              'timestamp': '2017-02-10T17:24:04.283Z'},
             {'processed': {'eulerAngles': [1.948553665755181,
                                            -0.01403613777322358,
                                            0.01932380767991558]},
              'raw': {'accel': [0.01380419824272394,
                                -0.001462434651330113,
                                0.01273023523390293],
                      'gyro': [0.09209229052066803,
                               0.07342914491891861,
                               0.01548820454627275]},
              'timestamp': '2017-02-10T17:24:04.293Z'}}]}

For every sample in samples array I need to extract array accel. I wrote the following code

    val el = db("samples").findOne(MongoDBObject("name" -> name))
    var t_series_seq: Array[Array[Double]] = Array()
    for (m <- el.get("samples")) t_series_seq :+ m("raw")("accel")

This is returning value foreach is not a member of AnyRef. I need to tell el.get("samples") type but I don't know how to tell it is a complex Map object.


Solution

  • Alright, so Casbah documentation is really bad. I actually got this by reading the chapter dedicated to using MongoDB with Scala in Scala for Data Science.

    My code would be the following:

    val dbSamples = db("samples").find(MongoDBObject("name" -> name))
    var timesSeries: Array[TimeSeries] = Array()
    for (s <- dbSamples) {
      var tSeries_seq: Array[Array[Double]] = Array()
      val measures = s.getAs[List[DBObject]]("samples").get
      for (m <- measures) {
        println(m.getAs[DBObject]("raw").get.getAs[List[Double]]("accel").get.toArray)
        tSeries_seq = tSeries_seq :+ m.getAs[DBObject]("raw").get.getAs[List[Double]]("accel").get.toArray
      }
      timesSeries = timesSeries :+ new TimeSeries(tSeries_seq, s.getAs[Integer]("valid").get)
    }
    timesSeries