「Java開発]MongoDBを操作(insert、update、delete、検索)する方法
Javaコード:
private static void mongoCftTest(){
try {
Mongo m = new Mongo( “172.17.2.201" , 27017 );
DB db = m.getDB( “cftdb" );
//collectionの作成
DBCollection collection = db.getCollection(“demoCollectionDemo");
BasicDBObject doc = new BasicDBObject();
doc.put(“name", “MongoDB");
doc.put(“type", “database");
doc.put(“count", 1);
BasicDBObject info = new BasicDBObject();
info.put(“x", 203);
info.put(“y", 102);
doc.put(“info", info);
//複数のレコードを挿入
for (int i=0; i < 100; i++) {
collection.insert(new BasicDBObject().append(“i", i));
}
//レコード数を取得
System.out.println(collection.getCount());
//Cursorで全てのドキュメントを取得
DBCursor cursor = collection.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
BasicDBObject query = new BasicDBObject();
query.put(“i", 56);
cursor = collection.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//検索条件 i>80
query = new BasicDBObject();
query.put(“i", new BasicDBObject(“$gt", 80)); // find all where i > 80
cursor = collection.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//更新条件i=56
query = new BasicDBObject();
query.put(“i", 56);
BasicDBObject update = new BasicDBObject();
update.put(“i", 560);
DBObject dbobj = collection.findAndModify(query, update);
System.out.println(dbobj);
//削除条件i=74
query = new BasicDBObject();
query.put(“i", 74);
collection.findAndRemove(query);
// indexの作成
collection.createIndex(new BasicDBObject(“i", 1)); // create index on “i", ascending
//indexのリストを取得
List<DBObject> list = collection.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
//データベースリスト
for (String s : m.getDatabaseNames()) {
System.out.println(s);
}
//collectionリスト
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
//データベース削除
//m.dropDatabase(“my_new_db");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}