1,下载驱动https://github.com/mongodb/mongo-java-driver/downloads,导入工程java中
2,建立测试代码
import java.net.UnknownHostException; import java.util.Set;
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;
public class TestMain {
public static void main(String[] args) throws UnknownHostException, MongoException { // Mongo m = new Mongo();//默认本地 // Mongo m = new Mongo("192.168.0.101");//默认端口 Mongo m = new Mongo("192.168.0.101",27017); //获取名为 alan 的数据库,不存在的情况下创建 DB db = m.getDB("alan"); //获取所有数据库,不显示无collection的db System.out.println("所有数据库名:"+m.getDatabaseNames()); //获取名为 testCollection 的collection(相当于表),不存在的情况下创建 DBCollection coll = db.getCollection("testCollection"); //向collection中插入值 (可以插条 ) BasicDBObject obj = new BasicDBObject(); obj.put("name","jone"); obj.put("sex", "male"); BasicDBObject info = new BasicDBObject(); info.put("height", 172); info.put("weight", 65); obj.put("other",info); coll.insert(obj); //获取数据库下所有的collection,不显示无数据的collection Set<String> colls = db.getCollectionNames(); for(String s : colls){ System.out.println(s); } //查询coll中全部记录 DBCursor ite = coll.find(); while(ite.hasNext()){ System.out.println(ite.next()); } //获取第一条记录 DBObject o = coll.findOne(); System.out.println(o);
//统计colletion的数据条数 System.out.println(coll.getCount()); // 查询 name位 mark的对象 BasicDBObject query = new BasicDBObject(); query.put("name", "mark"); DBCursor it = coll.find(query); while(it.hasNext()){ System.out.println(it.next()); } //查询height小于175,weight不等于65的对象 BasicDBObject query2 = new BasicDBObject(); query2.put("other.height", new BasicDBObject("$lt", 175)); query2.put("other.weight", new BasicDBObject("$ne",65)); DBCursor it2 = coll.find(query2); while(it2.hasNext()){ System.out.println(it2.next()); }
//更新操作 showData(coll); BasicDBObject old_obj = new BasicDBObject(); old_obj.put("name", "mark"); //这里的new_val对象一定要是find出的而不是new的,否则多字段的情况下就会丢失其它字段信息 DBObject new_val = coll.findOne(old_obj); new_val.put("name", "zhoulong"); /**这里只能修改一条满足条件的记录,而且根据API用updateMulti方法或者设置update第四个参数也无效, * 如果要批量跟新就要查询后,循环遍历更新了 */ coll.update(old_obj, new_val); showData(coll); //删除操作 showData(coll); BasicDBObject rmove = new BasicDBObject(); rmove.put("name", "jone"); coll.remove(rmove); //coll.findAndRemove(rmove);//可以用findAndRemove删除 ,不过这个方法之能删除一条符合条件的记录 showData(coll); }
//遍历数据 static void showData(DBCollection col) { DBCursor ite = col.find(); while(ite.hasNext()) { System.out.println(ite.next()); } } } 3,参考api,http://api.mongodb.org/java/2.5-pre-/index.html
4,用图形化的界面直观看看新建的库表和插入的数据