接触MONGDB,感觉用起来还挺好。今天做了一个小demo。
一、启动mongdb的服务
需要指定目录,这个目录是存放数据库的。
查看服务是否已经启动。可以查看端口(默认为27017)的状态。
二、编写JAVA代码
需要引入mongdb的JAR包。
编写代码:
public class demo { public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("company"); DBCollection collection = db.getCollection("employees"); BasicDBObject employee = new BasicDBObject(); employee.put("name", "Hannah"); employee.put("no", 2); collection.insert(employee); BasicDBObject searchEmployee = new BasicDBObject(); searchEmployee.put("no", 2); DBCursor cursor = collection.find(searchEmployee); while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("The Search Query has Executed!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }