标签:
// 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)
标签:
原文地址:http://www.cnblogs.com/rilley/p/5616026.html