初めて投稿します。よろしくお願いいたします。
JavaプログラムでmongoDBにJson記述のデータを格納したいと思っています
以前(MongoDB 3.0以前の非推奨のDB クラスを使用)は、(プログラム1)のようなコードで
Json型の文字列をDBObject型に変換してMongoDBに格納できていましたが
(プログラム1)
DBCollection coll;
String doc=”{\”math" : "77\”}”;
DB db;
DBCollection coll;
db = m.getDB("dbMongo10");
coll = db.getCollection("collectionMongo10");
DBObject json = (DBObject) JSON.parse(doc);
coll.insert(json);
現在(MongoDB 3.0から推奨のDBクラスを使用)でも、Json文字列をそのままinsertできないかと
やっています。
Document型のデータはinsertできますが(プログラム2)
(プログラム2)
MongoClient m = new MongoClient();
MongoDatabase db = m.getDatabase("dbMongo10");
MongoCollection collection = db.getCollection("collectionMongo10");
Document doc = new Document("math","75");
coll.insertOne(doc);
Json文字列そのまま(BSONまたはDocumentに変換)をinsertしたいのですができません。
(プログラム3)
String json = "{"math" : "77"}";
coll.insertOne(json);
(プログラム4−1)
String json = "{"math" : "77"}";
BSONObject bson = (BSONObject)com.mongodb.util.JSON.parse(json);
coll.insertOne(bson);
(プログラム4−2)
String json = "{"math" : "77"}";
DBObject dbObject = (DBObject)JSON.parse(json);
String json1 = JSON.serialize( dbObject );
DBObject bson = ( DBObject ) JSON.parse( json1 );
coll.insertOne(bson);
(プログラム5)
String json = "{"math" : "77"}";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document saveDocument = (Document) builder.parse(new InputSource(new StringReader(json)));
文字列(Json形式)でそのままDBに格納することはできないのでしょうか。
できない場合、Bson形式にて格納しておくとしたらどのようにプログラムしたら
いいでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。