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 Setcolls = 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 pets = new HashSet (); 76 pets.add("cat"); 77 pets.add("dog"); 78 Map favoriteMovies = new HashMap (); 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 Setpets; private Map 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 getPets() { return pets; } public void setPets(Set pets) { this.pets = pets; } public Map getFavoriteMovies() { return favoriteMovies; } public void setFavoriteMovies(Map 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"}}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4830/viewspace-2800444/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- mongodb-java-driver基本用法MongoDBJava
- MongoDB的基本用法MongoDB
- webpack的基本用法Web
- rematch的基本用法REM
- Promise的基本用法Promise
- mysqldump的基本用法MySql
- UIScrollView的基本用法UIView
- Promise基本用法Promise
- Git基本用法Git
- mongoose基本用法Go
- tcpdump基本用法TCP
- GORM基本用法GoORM
- 反射機制的基本用法反射
- MongoDB 及 PyMongo 的基本用法MongoDB
- react-redux的基本用法ReactRedux
- C++中& 的基本用法C++
- fork()函式的基本用法函式
- Git的17條基本用法Git
- JAVA的陣列基本用法Java陣列
- Hive的基本操作用法Hive
- Hibernate的基本API的用法API
- MySQL的mysqldump工具的基本用法MySql
- Spark的基本結構及SparkSQL元件的基本用法SparkSQL元件
- jquery ajax基本用法jQuery
- scp命令基本用法
- Jquery UI ---autocomplete的基本用法jQueryUI
- 【VUE】vue-router的基本用法Vue
- string 函式的基本用法函式
- dig 命令的基本用法(轉)
- DropDownList控制元件的基本用法控制元件
- table控制元件的基本用法控制元件
- Java裡的Character類的基本用法Java
- Quartz:基本用法總結quartz
- JAVA CDI @Inject基本用法Java
- React context基本用法ReactContext
- Object.defineProperty基本用法Object
- ElasticSearch之基本用法APIElasticsearchAPI
- vim配置及基本用法