public class MongoTest {
//查询
@Test
public void findTest() throws Exception{
Mongo mongo = new Mongo("localhost");
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("my");
DBCursor dbCursor = collection.find();
while(dbCursor.hasNext()){
DBObject dbObject = dbCursor.next();
Object object = dbObject.get("name");
System.out.println("name="+object);
}
mongo.close();
}
//新增
@Test
public void saveTest() throws Exception{
Mongo mongo = new Mongo("localhost");
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("my");
DBObject dbO = new BasicDBObject("name", 89);
collection.insert(dbO);
mongo.close();
}
//修改
@Test
public void updateTest() throws Exception{
Mongo mongo = new Mongo("localhost",27017);
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("my");
DBObject dbO = new BasicDBObject("_id", new ObjectId("52cf6208c534f85e3842552a"));
DBObject newDbO = new BasicDBObject("name", 7);
collection.update(dbO, newDbO);
mongo.close();
}
//删除
@Test
public void deleteTest() throws Exception{
Mongo mongo = new Mongo("localhost",27017);
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("my");
DBObject doO = new BasicDBObject("name",0);
collection.findAndRemove(doO);mongo.close();
}
}
nosql(mongo)增删改查
最新推荐文章于 2022-03-14 12:22:12 发布