mongodbscalacasbah

Specify datatypes while updating MongoDB document using Casbah


I have a MongoDB document that I need to update using Casbah for scala. My mongoDB document looks like

{"_id": ObjectId("58d86364fbb1bb2224cab56a"),
"record_interval": 
       [
          {
          "record_time": ISODate("2017-01-26T09:22:15.000Z"),
          "insert_time": ISODate("2017-03-26T12:57:08.610Z"),
          "reading1": 50.0,
          "reading2": 627.0
          }
       ],
"record_id": "1234",
"record_hour": ISODate("2017-01-26T09:00:00.000Z")
}

I inserted the above document using df.write methodology, so I was able to specify the schema with datatypes when I created the dataframe and was able to successfully insert the document with the the specified datatypes.

Now, I need to add an object inside the record interval array. I have a JSON string that I parsed as a DBObject

val DBobject: DBObject = JSON.parse(Json_String).asInstanceOf[DBObject]

The DBobject that looks like below

{
  "vib_temp": "55.0",
  "vib_voltage": "647.0",
  "message_time": "2017-01-26 03:48:52.000000",
  "etl_date_time": "2017-03-26 06:57:09.302000"
}

I added this DBObject into the record_interval array of the aforementioned document using the below code.

collection.update(MongoDBObject("_id" -> new ObjectId("58d86364fbb1bb2224cab56a"))
     ,$push("record_interval" -> new MongoDBObject(DBobject)))

I am able to update the desired document, but the datatypes of the elements record_time, insert_time, reading1 and reading2 are all strings. Whereas I would like to insert the object with appropriate datatypes. How do I specify the datatypes while updating the document? Thanks in advance


Solution

  • I found that the DBObject that I am trying to insert should have the values with the desired data type.

    Following worked for me.

    val Current_datetime = new DateTime()
    val message_time = new DateTime()
    
    collection.update(MongoDBObject("_id" -> new ObjectId("58d86364fbb1bb2224cab56a"))
         ,$push("record_interval" -> new MongoDBObject(
                       ,("vib_temp"->55.0)
                       ,("vib_voltage"->647.0)
                       ,("message_time"->message_time)
                       ,("etl_date_time"-> Current_datetime))))