Java MongoDB DriverでMongoDBを操作(insert、update、delete)する
DBに接続
MongoCliant cliant = new MongoCliant();
String host = “172.17.2.xxx";
MongoCliant cliant = new MongoCliant(host, 27017);
ドキュメント全件取得
String cntdoc = “";
FindIterable<Document> iterator = coll.find();
MongoCursor cursor = iterator.iterator();
while(cursor.hasNext()){
cntdoc += cursor.next();
cntdoc += System.getProperty(“line.separator");
}
System.out.println(cntdoc);
Create挿入
Document cntdoc = new Document();
doc.append(“name", “taro");
doc.append(“age", 31);
Date currentDate = new Date();
cntdoc.append(“lastModified", “ISODate(“+currentDate+")");
coll.insertOne(cntdoc);
Update更新
Document updDoc = new Document(“name", “hanmeda");
coll.updateOne(Filters.eq(“name", “ddds"), new Document(“$set", updDoc));
Upsert操作
Document updDoc = new Document(“name", “bikocft");
UpdateOptions option = new UpdateOptions().upsert(true);
coll.updateOne(Filters.eq(“name", “kuko"), new Document(“$set", updDoc), option);
Delete削除
//ドキュメント1件削除
coll.deleteOne(Filters.eq(“name", “sampledata"));
//ドキュメント全件削除
coll.deleteMany(Filters.eq(“name", “sampledata"));