MongoDB 将Json数据直接写入MongoDB的方法
import org.bson.Documentimport com.mongodb.casbah.{MongoClient, MongoCollection}
import com.mongodb.util.JSON;
// 构造一个Json字符串
val json = s"""{
|"school_code" : "${school_code}",
|"school_name" : "${school_name}",
|"teacher_idcard" : "${teacher_idcard}",
|"teacher_name" : "${teacher_name}"
|}
|""".stripMargin
val document:Document = Document.parse(json)
// 注意!com.mongodb.casbah.MongoCollection只支持写DBObject的子类,
// 不支持写入Document类的对象,可以使用com.mongodb.client.MongoCollection
// 写入Document类的对象,这里能写入是因为用了自定义的隐式转换函数,将
// Document转换成了DBObject
// 自定义的隐式转换函数
implicit def document2DBObject(doc: Document): DBObject = JSON.parse(doc.toJson).asInstanceOf
val collection: MongoCollection = MongoClient("10.4.120.83")("dbName")("collectionName")
collection.insert(document)
页:
[1]