上一篇文章:MongoDB入門學習
http://blog.csdn.net/rjfxd/article/details/12108909
一、準備工作
1、建立maven項目,添加所需依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.3</version>
</dependency>
當然也可以建立java project,下載然後拷貝jar檔案到lib下
2、開啟mongo服務,建立測試類別進行測試
二、完整源碼如下:
package com.shxt.mongo;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.bson.types.ObjectId;import org.junit.After;import org.junit.Before;import org.junit.Test;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.MongoClient;import com.mongodb.util.JSON; /** * MongDB之CRUD * @author 範曉東 * @ClassName: TestMongo * @Version 1.0 * @ModifiedBy * @Copyright shxt * @date 2013-9-27 下午08:21:49 * @description */public class TestMongo {private Mongo mg = null;private DB db;private DBCollection users;@Beforepublic void setUp() throws UnknownHostException {// 建立一個MongoDB的資料庫連接對象mg=new MongoClient("localhost", 27017);//驗證模式登入(如果不設定驗證模組,可直接登入)//想要登入驗證模組生效,需在命令列下輸入1->mongo 2->use admin 3->db.addUser("root","root123"); 4->db.auth("root","root123");DB admin=mg.getDB("admin");boolean bool =admin.authenticate("root", "root123".toCharArray());if (bool){//login success//獲得一個test的資料庫,如果該資料庫不存在,會自動建立db=mg.getDB("test");}// 擷取一個聚集集合DBCollection,相當於我們的資料庫表users = db.getCollection("users");}@Testpublic void testQuery() {//查詢所有的資料庫for (String name : mg.getDatabaseNames()) {System.out.println("dbName: " + name);}//查詢所有的聚集集合for (String name : db.getCollectionNames()) {System.out.println("collectionName: " + name);}//查詢所有的資料DBCursor cur = users.find();while (cur.hasNext()) {System.out.println(cur.next());}//其它System.out.println(cur.count());System.out.println(users.count());System.out.println(cur.getCursorId());System.out.println(JSON.serialize(cur));//JSON對象轉換 }@Testpublic void testQuery2(){ //根據id查詢List<DBObject> list=users.find(new BasicDBObject("_id", new ObjectId("5243871a0609f38c8a7a5ccd"))).toArray();System.out.println(list.get(0).get("name")); //根據age查詢,從第一條開始取,取3條資料BasicDBObject user = new BasicDBObject();user.put("age", new BasicDBObject("$gte", 20));DBCursor cur=users.find(user).skip(0).limit(3);System.out.println(cur.count());while (cur.hasNext()) {System.out.println(cur.next());} //查詢age!=25 //users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray(); //查詢age in 25/26/27 //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray(); //查詢age not in 25/26/27 //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray();//查詢存在age的資料 //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray(); //只查詢age屬性 //users.find(null, new BasicDBObject("age", true)).toArray(); //只查詢一條資料,多條取第一條 //users.findOne(); //users.findOne(new BasicDBObject("age", 26)); //users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true)); //查詢age=25的資料並刪除 //users.findAndRemove(new BasicDBObject("age", 25)); //查詢age=26的資料,並且修改name的值為abc //users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "abc"));}@Testpublic void testAdd() {DBObject user = new BasicDBObject();user.put("name", "fxd");user.put("age", 21);user.put("sex", "男");users.save(user);//查看是否添加成功DBCursor cur = users.find();while (cur.hasNext()) {System.out.println(cur.next());}}@Testpublic void testAdd2() {DBObject user1 = new BasicDBObject("name","張三");DBObject user2 = new BasicDBObject("age",20);users.insert(user1,user2);//查看是否添加成功DBCursor cur = users.find();while (cur.hasNext()) {System.out.println(cur.next());}}@Testpublic void testAdd3() {DBObject user1 = new BasicDBObject("name","張三");DBObject user2 = new BasicDBObject("age",20);List<DBObject> list = new ArrayList<DBObject>();list.add(user1);list.add(user2);users.insert(list);//查看是否添加成功DBCursor cur = users.find();while (cur.hasNext()) {System.out.println(cur.next());}}@Testpublic void testRemove(){ users.remove(new BasicDBObject("_id", new ObjectId("524378680609ad5717421c6a"))); //users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24)));}@Testpublic void update(){ //=update users set age=17 where name='fxd'; users.update( new BasicDBObject("name","fxd"),//new BasicDBObject().append("name","fxd"), new BasicDBObject("$set" ,new BasicDBObject("age",17)), false,//如果users中不存在age欄位,是否更新,false表示不更新 false//只修改第一條,true表示修改多條 ); }@Testpublic void update2(){ //批量修改,也可以用users.update(),把第四個參數改為true即可 //=update users set age=age+10 where name='fxd'; users.updateMulti( new BasicDBObject().append("name","fxd"), new BasicDBObject("$inc",new BasicDBObject("age", 10))); }@Afterpublic void tearDown() {if (mg != null) {if (db != null) {// 結束Mongo資料庫的事務請求try {db.requestDone();} catch (Exception e) {e.printStackTrace();}}try {mg.close();} catch (Exception e) {e.printStackTrace();}mg = null;db = null;}}}
參考:
http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html