標籤:doc teacher 行儲存 com cli name getc 隱式轉換函式 client
Json轉Bson
MongoDB中是以Bson資料格式進行儲存的,Json字串沒有辦法直接寫入MongoDB 可以將Json字串轉換成DBObject或者Document,然後寫入MongoDB
1、將Json字元轉換成com.mongodb.DBObject(準確的說是BasicDBObject)scala版本
import com.mongodb.DBObjectimport 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}" |} |""".stripMarginval collection: MongoCollection = MongoClient("10.4.120.83")("dbName")("collectionName")val bson: DBObject = JSON.parse(json).asInstanceOf[DBObject]collection.insert(bson) // mongodb casbah的寫法
java版本
import com.mongodb.MongoClient;import com.mongodb.DBObject;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;import com.mongodb.util.JSON;// 構造一個Json字串String json = " {" + " ‘school_code‘ : ‘111111‘, " + " ‘school_name‘ : ‘漢東政法大學‘, " + " ‘teacher_idcard‘ : ‘0000001‘, " + " ‘teacher_name‘ : ‘高育良‘ " + " } ";MongoClient mongoClient = new MongoClient("10.4.120.83", 27017);MongoDatabase database = mongoClient.getDatabase("dbName");MongoCollection<DBObject> collection = database.getCollection("collectionName", DBObject.class); DBObject bson = (DBObject)JSON.parse(json);collection.insertOne(bson);
2、將字串轉換成org.bson.Documentscala版本
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}" |} |""".stripMarginval 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[DBObject]val collection: MongoCollection = MongoClient("10.4.120.83")("dbName")("collectionName")collection.insert(document)
Java版本
import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;// 構造一個Json字串String json = " {" + " ‘school_code‘ : ‘111111‘, " + " ‘school_name‘ : ‘漢東政法大學‘, " + " ‘teacher_idcard‘ : ‘0000001‘, " + " ‘teacher_name‘ : ‘高育良‘ " + " } ";MongoClient mongoClient = new MongoClient("10.4.120.83", 27017);MongoDatabase database = mongoClient.getDatabase("dbName");MongoCollection<Document> collection = database.getCollection("collectionName"); Document document = Document.parse(json);collection.insertOne(document );
MongoDB 將Json資料直接寫入MongoDB的方法