MongoDBのJavaアプリケーションテスト
9572 ワード
もう言わないでソースを見て
実行結果:
usersのすべてのデータ{"_id":{"$oid":"511368549 a 6 cfc 804 af 1 d 1 b"},"name":"david","age":30,"sex":":"_id":{"$oid":""5113603 ad 49 a 60 eb 5 a 8479 be 7"},"name":"david","age":30,"sex":"男"}を問い合わせる
package corejava2.mongo.basic;
import java.net.UnknownHostException;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* TODO
*
* @author Master HaKu
* @version TODO
*/
public class MongoDbTest {
private Mongo mg = null;
private DB db;
private DBCollection users;
/**
* TODO
*/
public void init() {
try {
// mg=new Mongo();
mg = new Mongo("192.168.16.103", 27017);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// temp DB
db = mg.getDB("temp");
// users Collection
users = db.getCollection("users");
}
/**
* TODO
*/
public void destory() {
if (mg != null) {
mg.close();
}
mg = null;
db = null;
users = null;
System.gc();
}
/**
* <b>function:</b>
*
* @author Master HaKu
* @createDate 2013-02-07
*/
public void queryAll() {
print(" users ");
// Db
DBCursor cur = users.find();
while (cur.hasNext()) {
print(cur.next());
}
}
/**
*
* <b>function:</b>
*
* @author Master HaKu
* @createDate 2013-02-07
*/
public void add() {
queryAll();
print("count:" + users.count());
DBObject user = new BasicDBObject();
user.put("name", "david");
user.put("age", 30);
// users.save(user);
// print(users.save(user).getN());
user.put("sex", " ");
print(users.save(user).getN());
print("count:" + users.count());
queryAll();
}
/**
*
* <b>function:</b>
*
* @author Master HaKu
* @createDate 2013-02-07
*/
public void remove() {
queryAll();
print(" id = 51135e5649a6af891f85f8f3:"
+ users.remove(
new BasicDBObject("_id", new ObjectId("51135e5649a6af891f85f8f3")))
.getN());
queryAll();
}
public void print(Object o) {
System.out.println(o);
}
public void start() {
init();
add();
//destory();
remove();
queryAll();
}
/**
* TODO
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MongoDbTest t = new MongoDbTest();
t.start();
}
}
実行結果:
usersのすべてのデータ{"_id":{"$oid":"511368549 a 6 cfc 804 af 1 d 1 b"},"name":"david","age":30,"sex":":"_id":{"$oid":""5113603 ad 49 a 60 eb 5 a 8479 be 7"},"name":"david","age":30,"sex":"男"}を問い合わせる