Java操作MongoDB

jopen 11年前

1.加载驱动

驱动:mongo-java-driver
地址:https://github.com/mongodb/mongo-java-driver/downloads

2.获取连接

(1) Mongo mongo = new Mongo();                      //默认形式:127.0.0.1:27017  (2) Mongo mongo = new Mongo("192.168.0.101");           //默认端口:27017  (3) Mongo mongo = new Mongo("192.168.0.101",27017); //完整形式

3.基本操作

//获取所有数据库  mongo.getDatabaseNames();    //获取数据库person  DB db = mongo.getDB("person");    //获取所有的集合(表)  db.getCollectionNames();    //获取集合user  DBCollection users = db.getCollection("user");    //获取user集合中文档的个数  int count = users.getCount();    //增加新的记录  BasicDBObject userObj = new BasicDBObject();  userObj.put("username", "柯南");  userObj.put("age", 20);  userObj.put("地址", "日本东京");    collection.insert(userObj);    //删除指定条件的文档  BasicDBObject removeObj = new BasicDBObject();  removeObj.put("age", new BasicDBObject("$lt",22));      //年龄小于22    collection.remove(removeObj);    //修改(不再详细举例)  collection.update(BasicDBObject oldObj,BasicDBObject newObj);    //查询user集合下,所有记录  DBCursor dbCursor = users.find();  while(dbCursor.hasNext()){      System.out.println(dbCursor.next());  }    //查询user集合下,符合指定条件的记录  BasicDBObject query = new BasicDBObject();  query.put("name", "duandoudou");  DBObject userTemp = collection.findOne(query);    System.out.println(userTemp);