Error entering document in mongodb from scala

Trying to insert mongodb from scala into the database. below codes do not create db or collection. tried also using test db by default. How can 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
source share
2 answers

At first glance, things look OK in the code, although you have this wandering code def addMongo(): Unit = { at the top. I put off the suggestion of finding errors here ... Two notes:

1) save()and insert()are additional operations - you only need one. insert()will always try to create a new document ... save()will create it if the field is _idnot set and will update the submitted _idif this happens.

2) Mongo . , MongoDB , . getLastError() . Java MongoDB , , , "" (, ). Java- ( Scala, , ):

   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

MongoDB Write Durability, Java.

Scala , (Casbah), Java scala.

, , (), .

+6

addMongo main. :

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!
}
+4

Source: https://habr.com/ru/post/1765307/


All Articles