开发者

What ways to perform CRUD operations in Scala with mongoDB

开发者 https://www.devze.com 2023-01-16 21:22 出处:网络
what are the methods/drivers i can use to perform CRUD operations? Atm, i am only successful with the Create function, ie

what are the methods/drivers i can use to perform CRUD operations? Atm, i am only successful with the Create function, ie

DBObbject.put("field","value")

Common sense suggests that find() should stand for retrieve, but using it gives the following error

value find is not a member of com.mongodb.BasicDBObject

All and any help appreciated.

EDIT #1:

I also was able to perf开发者_JAVA百科orm retrieve, but I retrieved the whole document, and not a specific field.

var mongo = new Mongo()
var databaseName = mongo.getDB("DBName")
var collectionName = databaseName.getCollection("namecollection")
var testdbObject = new BasicDBObject()

testdbObject.put("userId", "5678")
var cursor = collectionName.find(testdbObject)

println(cursor.next())

EDIT #2: Field based retrieval. IMO, Can put inside loop and print all. Havent tried the loop thing.

var result = collectionName.findOne()
println(result.get("userId").toString)

Thanks.


The presentation by Brendan McAdams at this link will give you most of the idea of how to use scala+mongoDB together.


For the benefit of the programming public: CRD operations.

The create operation:

def addToMongo(): Unit = {    
        dbObject.put("name", "mongo")
        dbObject.put("type", "db")        
        collectionName.insert(dbObject)
     }

The retrieve operation:

def retrieveMongo(): Unit = {    
    var result = collectionName.findOne()
    println(result.get("fieldName").toString)

  }

The Delete Operation.

def deleteMongo(): Unit = {
    var deleteQuery = new BasicDBObject
    var tempObject = new BasicDBObject
    deleteQuery.put("requestType", "temp");
  var cursor = new DBCursor(collectionName, deleteQuery, tempObject)
    while (cursor.hasNext()) {
      collectionName.remove(cursor.next())
    }

I was unable to come-up with a solution for the Update. Sorry about that.

0

精彩评论

暂无评论...
验证码 换一张
取 消