码迷,mamicode.com
首页 > 数据库 > 详细

Scala操作MongoDB

时间:2016-06-25 12:17:40      阅读:1198      评论:0      收藏:0      [点我收藏+]

标签:

 

Scala操作MongoDB

 

 

// Maven
<dependencies>

    <dependency>

        <groupId>org.mongodb</groupId> <artifactId>casbah</artifactId> <version>3.1.1</version>

    </dependency>

</dependencies>

 

 

// Sbt
libraryDependencies += "org.mongodb" %% "casbah" % "3.1.1"

 

 

// Lib
 import com.mongodb.casbah.Imports._

 

 

// CONNECTION
//val mongoClient= MongoClient("localhost", 27017)
val uri = MongoClientURI("mongodb://localhost:27017/")
val mongoClient = MongoClient(uri)

 

 


// USE COLLECTION
val db = mongoClient("test")
db.collectionNames
val coll = db("abc")




// INSERT
val user1 = MongoDBObject("name" -> "user1", "email" -> "user1@test.com")
val user2 = MongoDBObject("name" -> "user2", "email" -> "user2@test.com")
val user3 = MongoDBObject("name" -> "user3", "email" -> "user3@test.com")

coll.insert(user1)
coll.insert(user2)
coll.insert(user3)

 



// SELECT
coll.count() //读取总记录数
coll.find().foreach(println)

val query1 =MongoDBObject("name" -> "user1")
coll.findOne(query1)

 



// UPDATE
val update1 = MongoDBObject("email" -> "user1@test.com")
val result1 = coll.update(query1, update1)

 

// upsert=true,如果不存在就insert
// val result = coll.update( query, update, upsert=true )

 

// 批量更新
val query3 = MongoDBObject("name" -> "user2", "email" -> "user2@test.com")
val update3 = $set("email" -> "user1@test.com")
val result3 = coll.update(query3, update3, multi=true)

 

 


// DELETE
val query2 = MongoDBObject("name" -> "user2" )
val result2 = coll.remove(query2)

 

 

 

 

   

Scala操作MongoDB

标签:

原文地址:http://www.cnblogs.com/rilley/p/5616026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!