mongodb-java-driver基本用法
1、先下载mongodb-java-driver 目前最新版本是2.9.3
2、下面是基本的CRUD示例代码:
1 package com.cnblogs.yjmyzz.cache.test; 2 3 import com.google.gson.Gson; 4 import com.mongodb.BasicDBObject; 5 import com.mongodb.DB; 6 import com.mongodb.DBCollection; 7 import com.mongodb.DBCursor; 8 import com.mongodb.DBObject; 9 import com.mongodb.Mongo; 10 import com.mongodb.util.JSON; 11 12 import java.net.UnknownHostException; 13 import java.util.Calendar; 14 import java.util.Date; 15 import java.util.HashMap; 16 import java.util.HashSet; 17 import java.util.Map; 18 import java.util.Set; 19 20 import org.junit.Test; 21 22 public class TestMongoDriver { 23 24 @Test 25 public void testCRUD() throws UnknownHostException { 26 // 连接到mongodb 27 Mongo mongo = new Mongo("localhost", 27017); 28 29 // 打开数据库test 30 DB db = mongo.getDB("test"); 31 32 // 遍历所有集合的名字 33 Set<String> colls = db.getCollectionNames(); 34 for (String s : colls) { 35 System.out.println(s); 36 // 先删除所有Collection(类似于关系数据库中的"表") 37 if (!s.equals("system.indexes")) { 38 db.getCollection(s).drop(); 39 } 40 } 41 42 // 取得集合emp(若:emp不存在,mongodb将自动创建该集合) 43 DBCollection coll = db.getCollection("emp"); 44 45 // delete all 46 DBCursor dbCursor = coll.find(); 47 for (DBObject dbObject : dbCursor) { 48 coll.remove(dbObject); 49 } 50 51 // create 52 BasicDBObject doc = new BasicDBObject("name", "杨俊明").append("sex", "男") 53 .append("address", 54 new BasicDBObject("postcode", "201202").append( 55 "street", "田林路888号").append("city", "上海")); 56 coll.insert(doc); 57 58 // retrieve 59 BasicDBObject docFind = new BasicDBObject("name", "杨俊明"); 60 DBObject findResult = coll.findOne(docFind); 61 System.out.println(findResult); 62 63 // update 64 doc.put("sex", "MALE");// 把sex属性从"男",改成"MALE" 65 coll.update(docFind, doc); 66 findResult = coll.findOne(docFind); 67 System.out.println(findResult); 68 69 coll.dropIndexes();// 先删除所有索引 70 // create index 71 coll.createIndex(new BasicDBObject("name", 1)); // 1代表升序 72 73 // 复杂对象 74 UserData userData = new UserData("jimmy", "123456"); 75 Set<String> pets = new HashSet<String>(); 76 pets.add("cat"); 77 pets.add("dog"); 78 Map<String, String> favoriteMovies = new HashMap<String, String>(); 79 favoriteMovies.put("dragons", "Dragons II"); 80 favoriteMovies.put("avator", "Avator I"); 81 userData.setFavoriteMovies(favoriteMovies); 82 userData.setPets(pets); 83 userData.setBirthday(getDate(1990, 5, 1)); 84 BasicDBObject objUser = new BasicDBObject("key", "jimmy").append( 85 "value", toDBObject(userData)); 86 coll.insert(objUser); 87 System.out.println(coll.findOne(objUser)); 88 } 89 90 /** 91 * 将普通Object对象转换成mongodb的DBObject对象 92 * 93 * @param obj 94 * @return 95 */ 96 private DBObject toDBObject(Object obj) { 97 Gson gson = new Gson(); 98 String json = gson.toJson(obj); 99 return (DBObject) JSON.parse(json); 100 } 101 102 /** 103 * 获取指定日期 104 * 105 * @param year 106 * @param month 107 * @param day 108 * @return 109 */ 110 private Date getDate(int year, int month, int day) { 111 Calendar calendar = Calendar.getInstance(); 112 calendar.clear(); 113 calendar.set(year, month - 1, day); 114 return calendar.getTime(); 115 116 } 117 118 }
其中,为了演示复杂对象的持久化,类UserData定义如下:
package com.cnblogs.yjmyzz.cache.test; 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"}}
延伸阅读:
mondodb-java-driver 官方在线文档
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。