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
coll.insert(MongoDBObject("name" -> "user1", "email" -> "user1@test.com"))
coll.insert(MongoDBObject("name" -> "user1", "email" -> "user1@test.com"))
coll.insert(MongoDBObject("name" -> "user1", "email" -> "user1@test.com"))
// 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
coll.remove(MongoDBObject("name" -> "user2" ))