標籤:mongodb 資料庫
2013年,寫的CRUD太簡單了,今天在原來的基礎上,稍微完善了下,用了更多文法,比如排序sort、in語句等。
參考了《Mongodb權威指南-第1版-高清》,等下上傳到CSDN下載頻道,免積分下載。
代碼寫得夠清晰了,不再過多解釋。
package mongodb;import java.net.UnknownHostException;import java.util.Date;import com.mongodb.BasicDBList;import com.mongodb.BasicDBObject;import com.mongodb.CommandResult;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.Mongo;import com.mongodb.WriteResult;/** * MongoDB-CRUD Demo。 * * */public class MongoDBDemo {// /////////////資料庫地址常量//////////////////////** * 資料庫地址 */public static final String DEFAULT_HOST = "localhost";// localhost/** * 連接埠號碼 */public static final int DEFAULT_PORT = 27017;// //////////////資料庫名稱和集合常量//////////////////** * 資料庫名稱 */public static final String DB_BLOG = "blog";/** * 集合名稱 */public static final String DB_BLOG_COLLECTION = "article";// /////////////文章Article的屬性名稱常量//////////////////////** * 標題 */public static final String TITLE = "title";/** * 內容 */public static final String CONTENT = "content";/** * 作者 */public static final String AUTHOR = "author";/** * 日期 */public static final String DATE = "date";public static final String ID = "id";public static void main(String[] args) throws UnknownHostException {Mongo mogo = new Mongo(DEFAULT_HOST, DEFAULT_PORT);// 獲得資料庫DB blogDb = mogo.getDB(DB_BLOG);DBCollection articleCollection = blogDb.getCollection(DB_BLOG_COLLECTION);buildThreeArticles(articleCollection);// 尋找並列印作者為"FansUnion"的文章BasicDBObject searchArticleByAuthor = new BasicDBObject();searchArticleByAuthor.append(AUTHOR, "FansUnion");demoFindByField(articleCollection, searchArticleByAuthor);demoFindAndSort(articleCollection, searchArticleByAuthor);BasicDBObject searchArticleById = new BasicDBObject();searchArticleById.append(ID, 3L);demoFindById(articleCollection, searchArticleById);demoFindSpecialField(articleCollection, searchArticleById);demoFindWithIn(articleCollection);demoUpdateWithTwoWay(articleCollection, searchArticleByAuthor);demoRemove(articleCollection);// 集合中的文檔數量long count = articleCollection.count();println("刪除了剛剛建立的3條記錄,剩餘count=" + count);// 關閉串連mogo.close();}//刪除資料private static void demoRemove(DBCollection articleCollection) {// 刪除BasicDBObject removeCondition = new BasicDBObject();removeCondition.append(AUTHOR, "FansUnion");articleCollection.remove(removeCondition);BasicDBObject removeCondition2 = new BasicDBObject();removeCondition.append(TITLE, "HelloWorld");// 刪除,並查看是否有報錯WriteResult writeResult = articleCollection.remove(removeCondition2);CommandResult commandResult = writeResult.getLastError();println("查看error資訊,發現err欄位為空白" + commandResult.toString());BasicDBObject removeAll = new BasicDBObject();articleCollection.remove(removeAll);}//2種方式更新對象private static void demoUpdateWithTwoWay(DBCollection articleCollection,BasicDBObject searchArticleByAuthor) {// 把標題為"HelloWorld"的文章的作者,修改為“小雷”println("把標題為HelloWorld的文章的作者,修改為小雷,只修改AUTHOR1個欄位");// 查詢條件:標題為"HelloWorld"BasicDBObject updateCondition = new BasicDBObject();searchArticleByAuthor.append(TITLE, "HelloWorld");BasicDBObject newHelloWorldArticle = new BasicDBObject();newHelloWorldArticle.append(AUTHOR, "小雷");// 第1種方式-修改,只修改指定的欄位("$set","$inc"都是修改器)// update Article set author="小雷" where title=‘HelloWorld‘DBObject updateSetValue = new BasicDBObject("$set",newHelloWorldArticle);articleCollection.update(updateCondition, updateSetValue);// 列印第1次修改過的"HelloWorld"文章DBObject helloWordlArticle2 = articleCollection.findOne(updateCondition);print(helloWordlArticle2);// 第2種方式-修改// update Article set author="小雷",title=null,content=null,date=null// where title=‘HelloWorld‘println("把標題為HelloWorld的文章的作者,修改為小雷,修改了所有的欄位");articleCollection.update(updateCondition, newHelloWorldArticle);DBObject helloWordlArticle = articleCollection.findOne(updateCondition);// 列印第2次修改過的"HelloWorld"文章print(helloWordlArticle);}//Mongodb中的in語句private static void demoFindWithIn(DBCollection articleCollection) {// IN查詢println("尋找並列印ID為1和2的文章");// List list = Arrays.asList(1,2);// Long[] array= new Long[]{1L,2L};BasicDBList values = new BasicDBList();values.add(1);values.add(2);DBObject inQuery = new BasicDBObject("$in", values);DBObject con = new BasicDBObject();con.put(ID, inQuery);DBCursor cursorIdArray = articleCollection.find(con);println("個數:" + cursorIdArray.count());while (cursorIdArray.hasNext()) {print(cursorIdArray.next());}}//查詢特定的欄位private static void demoFindSpecialField(DBCollection articleCollection,BasicDBObject searchArticleById) {println("尋找並列印ID為3的文章2,只查詢TITLE欄位");BasicDBObject b = new BasicDBObject();b.append(TITLE, 1);DBCursor cursor3 = articleCollection.find(searchArticleById, b);println("個數:" + cursor3.count());while (cursor3.hasNext()) {print(cursor3.next());}// cursor3.close();//在沒有這行代碼的情況下,同樣的程式,出現了1次,個數為4,仔細看,發現他們的內建ID不一樣// 可能是上一次執行的刪除,還沒有完成?//這個地方是一個疑問,但是複現不了}//根據ID尋找對象private static BasicDBObject demoFindById(DBCollection articleCollection,BasicDBObject searchArticleById) {// 尋找並列印ID為3的文章println("尋找並列印ID為3的文章");DBCursor cursor2 = articleCollection.find(searchArticleById);println("個數:" + cursor2.count());while (cursor2.hasNext()) {print(cursor2.next());}cursor2.close();return searchArticleById;}//尋找對象,並排序private static void demoFindAndSort(DBCollection articleCollection,BasicDBObject searchArticleByAuthor) {// 尋找並列印作者為"FansUnion"的文章,按照ID降序排列println("尋找並列印作者為FansUnion的文章,降序排列,查詢出來的ID一次為3,2,1");BasicDBObject orderByIdDesc = new BasicDBObject();orderByIdDesc.append(ID, -1);DBCursor cursorIdDesc = articleCollection.find(searchArticleByAuthor).sort(orderByIdDesc);while (cursorIdDesc.hasNext()) {print(cursorIdDesc.next());}}//根據欄位尋找對象private static void demoFindByField(DBCollection articleCollection,BasicDBObject searchArticleByAuthor) {println("尋找並列印作者為FansUnion的文章,查詢出來的ID一次為1,2,3");DBCursor cursor = articleCollection.find(searchArticleByAuthor);while (cursor.hasNext()) {print(cursor.next());}cursor.close();// 網上和書中的的例子,沒有關閉遊標,官方JDK文檔“kills the current cursor on// the server.”}// 構造3個文章,插入的ID順序是1,2,3private static void buildThreeArticles(DBCollection articleCollection) {BasicDBObject article = buildArticle("做好社會主義的接班人", "好好學習,天天向上","FansUnion", new Date(), 1L);BasicDBObject article2 = buildArticle("做好資本主義的掘墓人", "拚命幹活,時時向上","FansUnion", new Date(), 2L);BasicDBObject article3 = buildArticle("HelloWorld","I am a MongoDb demo.", "FansUnion", new Date(), 3L);// 增加若干文章articleCollection.insert(article);articleCollection.insert(article2);articleCollection.insert(article3);println("插入文章的個數:" + articleCollection.count());}// 列印對象private static void print(DBObject article) {// println("-----------------------");println("內建ID:" + article.get("_id"));println("標題:" + article.get(TITLE));println("內容:" + article.get(CONTENT));println("" + article.get(AUTHOR));println("日期:" + article.get(DATE));println("ID:" + article.get(ID));println("-----------------------");}private static void println(Object object) {System.out.println(object);}/** * 構造1個文章對象 * * @param title * 標題 * @param content * 內容 * @param author * 作者 * @param date * 日期 * @return 文章對象 */private static BasicDBObject buildArticle(String title, String content,String author, Date date, Long id) {BasicDBObject article = new BasicDBObject();article.append(TITLE, title);article.append(CONTENT, content);article.append(AUTHOR, author);article.append(DATE, date);article.append(ID, id);return article;}}
代碼執行結果
插入文章的個數:3
尋找並列印作者為FansUnion的文章,查詢出來的ID一次為1,2,3
內建ID:561baace3aea5b925fddc83c
標題:做好社會主義的接班人
內容:好好學習,天天向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:1
-----------------------
內建ID:561baace3aea5b925fddc83d
標題:做好資本主義的掘墓人
內容:拚命幹活,時時向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:2
-----------------------
內建ID:561baace3aea5b925fddc83e
標題:HelloWorld
內容:I am a MongoDb demo.
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:3
-----------------------
尋找並列印作者為FansUnion的文章,降序排列,查詢出來的ID一次為3,2,1
內建ID:561baace3aea5b925fddc83e
標題:HelloWorld
內容:I am a MongoDb demo.
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:3
-----------------------
內建ID:561baace3aea5b925fddc83d
標題:做好資本主義的掘墓人
內容:拚命幹活,時時向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:2
-----------------------
內建ID:561baace3aea5b925fddc83c
標題:做好社會主義的接班人
內容:好好學習,天天向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:1
-----------------------
尋找並列印ID為3的文章
個數:1
內建ID:561baace3aea5b925fddc83e
標題:HelloWorld
內容:I am a MongoDb demo.
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:3
-----------------------
尋找並列印ID為3的文章2,只查詢TITLE欄位
個數:1
內建ID:561baace3aea5b925fddc83e
標題:HelloWorld
內容:null
null
日期:null
ID:null
-----------------------
尋找並列印ID為1和2的文章
個數:2
內建ID:561baace3aea5b925fddc83c
標題:做好社會主義的接班人
內容:好好學習,天天向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:1
-----------------------
內建ID:561baace3aea5b925fddc83d
標題:做好資本主義的掘墓人
內容:拚命幹活,時時向上
FansUnion
日期:Mon Oct 12 20:42:54 CST 2015
ID:2
-----------------------
把標題為HelloWorld的文章的作者,修改為小雷,只修改AUTHOR1個欄位
內建ID:561baace3aea5b925fddc83c
標題:做好社會主義的接班人
內容:好好學習,天天向上
小雷
日期:Mon Oct 12 20:42:54 CST 2015
ID:1
-----------------------
把標題為HelloWorld的文章的作者,修改為小雷,修改了所有的欄位
內建ID:561baace3aea5b925fddc83c
標題:null
內容:null
小雷
日期:null
ID:null
-----------------------
查看error資訊,發現err欄位為空白{ "serverUsed" : "localhost/127.0.0.1:27017" , "n" : 1 , "connectionId" : 1 , "err" : null , "ok" : 1.0}
刪除了剛剛建立的3條記錄,剩餘count=0
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Mongodb總結2-Java版本的HelloWorld-CRUD例子