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" -> "[email protected]") val user2 = MongoDBObject("name" -> "user2", "email" -> "[email protected]") val user3 = MongoDBObject("name" -> "user3", "email" -> "[email protected]") 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" -> "[email protected]") val result1 = coll.update(query1, update1)
// upsert=true,如果不存在就insert // val result = coll.update( query, update, upsert=true )
// 批量更新 val query3 = MongoDBObject("name" -> "user2", "email" -> "[email protected]") val update3 = $set("email" -> "[email protected]") val result3 = coll.update(query3, update3, multi=true)
// DELETE
val query2 = MongoDBObject("name" -> "user2" ) val result2 = coll.remove(query2)
时间: 2024-10-25 02:51:57