tags:

views:

72

answers:

2

Trying to insert into a mongodb database from scala. the below codes dont create a db or collection. tried using the default test db too. how do i perform CRUD operations?

object Store {
      def main(args: Array[String]) = {
        def addMongo(): Unit = {
          var mongo = new Mongo()
          var db = mongo.getDB("mybd")
          var coll = db.getCollection("somecollection")
          var obj = new BasicDBObject()
      obj.put("name", "Mongo")
      obj.put("type", "db")
      coll.insert(obj)
      coll.save(obj)
      println("Saved") //to print to console
        }
    }
+3  A: 

On a first glance things look OK in your code although you have that stray def addMongo(): Unit = { code at the top. I'll defer to a suggestion on looking for errors here.... Two items of note:

1) save() and insert() are complementary operations - you only need one. insert() will always attempt to create a new document ... save() will create one if the _id field isn't set, and update the represented _id if it does.

2) Mongo clients do not wait for an answer to a write operation by default. It is very possible & likely that an error is occurring within MongoDB causing your write to fail. the getLastError() command will return the result of the last write operation on the current connection. Because MongoDB's Java driver uses connection pools you have to tell it to lock you onto a single connection for the duration of an operation you want to run 'safely' (e.g. check result). This is the easiest way from the Java driver (in Scala, sample code wise, though):

   mongo.requestStart() // lock the connection in
   coll.insert(obj) // attempt the insert
   getLastError.throwOnError() // This tells the getLastError command to throw an exception in case of an error
   mongo.requestDone() // release the connection lock

Take a look at this excellent writeup on MongoDB's Write Durability, which focuses specifically on the Java Driver.

You may also want to take a look at the Scala driver I maintain (Casbah) which wraps the Java driver and provides more scala functionality.

We provide among other things an execute-around-method version of the safe write concept in safely() which makes things a lot easier for testing for writes' success.

Brendan W. McAdams
+2  A: 

You just missed the addMongo call in main. The fix is trivial:

object Store {
  def main(args: Array[String]) = {
    def addMongo(): Unit = {
      var mongo = new Mongo()
      var db = mongo.getDB("mybd")
      var coll = db.getCollection("somecollection")
      var obj = new BasicDBObject()
      obj.put("name", "Mongo")
      obj.put("type", "db")
      coll.insert(obj)
      coll.save(obj)
      println("Saved") //to print to console
    }

    addMongo // call it!
}
Alexander Azarov