1、先下载mongodb-java-driver ,可以百度搜索maven仓库的mongoDB的java语言的driver。
2、下面是基本的CRUD示例代码:
import com.google.gson.Gson; 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.util.JSON; import java.net.UnknownHostException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Test; public class TestMongoDriver { @Test public void testCRUD() throws UnknownHostException { // 连接到mongodb Mongo mongo = new Mongo("localhost", 27017); // 打开数据库test DB db = mongo.getDB("test"); // 遍历所有集合的名字 Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s); // 先删除所有Collection(类似于关系数据库中的"表") if (!s.equals("system.indexes")) { db.getCollection(s).drop(); } } // 取得集合emp(若:emp不存在,mongodb将自动创建该集合) DBCollection coll = db.getCollection("emp"); // delete all DBCursor dbCursor = coll.find(); for (DBObject dbObject : dbCursor) { coll.remove(dbObject); } // create BasicDBObject doc = new BasicDBObject("name", "杨俊明").append("sex", "男") .append("address", new BasicDBObject("postcode", "201202").append( "street", "田林路888号").append("city", "上海")); coll.insert(doc); // retrieve BasicDBObject docFind = new BasicDBObject("name", "杨俊明"); DBObject findResult = coll.findOne(docFind); System.out.println(findResult); // update doc.put("sex", "MALE");// 把sex属性从"男",改成"MALE" coll.update(docFind, doc); findResult = coll.findOne(docFind); System.out.println(findResult); coll.dropIndexes();// 先删除所有索引 // create index coll.createIndex(new BasicDBObject("name", 1)); // 1代表升序 // 复杂对象 UserData userData = new UserData("jimmy", "123456"); Set<String> pets = new HashSet<String>(); pets.add("cat"); pets.add("dog"); Map<String, String> favoriteMovies = new HashMap<String, String>(); favoriteMovies.put("dragons", "Dragons II"); favoriteMovies.put("avator", "Avator I"); userData.setFavoriteMovies(favoriteMovies); userData.setPets(pets); userData.setBirthday(getDate(1990, 5, 1)); BasicDBObject objUser = new BasicDBObject("key", "jimmy").append( "value", toDBObject(userData)); coll.insert(objUser); System.out.println(coll.findOne(objUser)); } /** * 将普通Object对象转换成mongodb的DBObject对象 * * @param obj * @return */ private DBObject toDBObject(Object obj) { Gson gson = new Gson(); String json = gson.toJson(obj); return (DBObject) JSON.parse(json); } /** * 获取指定日期 * * @param year * @param month * @param day * @return */ private Date getDate(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(year, month - 1, day); return calendar.getTime(); } }
其中,为了演示复杂对象的持久化,类UserData定义如下:
import java.io.Serializable; import java.util.Date; import java.util.Map; import java.util.Set; public class UserData implements Serializable { private static final long serialVersionUID = -4770493237851400594L; private String userName; private String password; private Set<String> pets; private Map<String, String> favoriteMovies; private Date birthday; public UserData() { } public UserData(String userName, String passWord) { this.userName = userName; this.password = passWord; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<String> getPets() { return pets; } public void setPets(Set<String> pets) { this.pets = pets; } public Map<String, String> getFavoriteMovies() { return favoriteMovies; } public void setFavoriteMovies(Map<String, String> favoriteMovies) { this.favoriteMovies = favoriteMovies; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
运行效果如下:
emp system.indexes { "_id" : { "$oid" : "53d34795744ec171e7f6980a"} , "name" : "杨俊明" , "sex" : "男" , "address" : { "postcode" : "201202" , "street" : "田林路888号" , "city" : "上海"}} { "_id" : { "$oid" : "53d34795744ec171e7f6980a"} , "name" : "杨俊明" , "sex" : "MALE" , "address" : { "postcode" : "201202" , "street" : "田林路888号" , "city" : "上海"}} { "_id" : { "$oid" : "53d34796744ec171e7f6980b"} , "key" : "jimmy" , "value" : { "userName" : "jimmy" , "password" : "123456" , "pets" : [ "cat" , "dog"] , "favoriteMovies" : { "dragons" : "Dragons II" , "avator" : "Avator I"} , "birthday" : "May 1, 1990 12:00:00 AM"}}