MongoDB API实现增删改查
一,代码实现
1 import com.mongodb.DBCollection; 2 import com.mongodb.MongoClient; 3 import java.net.UnknownHostException; 4 5 6 public class MongDBUtile { 7 /** 8 * MongoClient是线程安全的 9 * Mongo是非线程安全的 10 * 目前mongodb API中已经建议用MongoClient替代Mongo 11 */ 12 private MongoClient mongoClient = null; 13 14 15 /** 16 * 指定数据库的指定集合 17 * @param dbName 18 * @param collectionName 19 * @return 20 */ 21 public DBCollection getDBCollection(String dbName, String collectionName) { 22 return mongoClient.getDB(dbName).getCollection(collectionName); 23 } 24 25 /** 26 * 单例模式获取MongoClient 27 */ 28 private static MongDBUtile getInstance = null; 29 30 public static MongDBUtile getInstance(String host, int port){ 31 getInstance = new MongDBUtile(host,port); 32 return getInstance; 33 } 34 35 private MongDBUtile(String host, int port){ 36 if(mongoClient == null){ 37 synchronized (MongDBUtile.class) { 38 if (mongoClient == null) { 39 initConn(host, port); 40 } 41 } 42 } 43 } 44 45 /** 46 * 初始化MongoClient 47 * @param host 48 * @param port 49 */ 50 private void initConn(String host, int port) { 51 try { 52 mongoClient = new MongoClient(host,port); 53 } catch (UnknownHostException e) { 54 e.printStackTrace(); 55 } 56 } 57 58 }
1.1 插入
1 /** 2 * 新增 一条记录 3 * @param dbCollection 4 */ 5 public static void addOne(DBCollection dbCollection){ 6 DBObject documents = new BasicDBObject("name","张三").append("age", 45).append("sex", "男").append("address", 7 new BasicDBObject("postCode", 100000).append("street", "深南大道888号").append("city", "深圳")); 8 dbCollection.insert(documents); 9 } 10 11 /** 12 * 批量新增记录:可以使用各种数据类型 13 * @param dbCollection 14 */ 15 public static void addList(DBCollection dbCollection){ 16 List<DBObject> listdbo= new ArrayList<>(); 17 DBObject dbObject = new BasicDBObject(); 18 dbObject.put("name", "老王"); 19 // 可以直接保存List类型 20 List<String> list = new ArrayList<>(); 21 list.add("老王1"); 22 list.add("老王2"); 23 dbObject.put("remark", list); 24 listdbo.add(dbObject); 25 26 dbObject = new BasicDBObject(); 27 // 可以直接保存map 28 Map<String,List<String>> map = new HashMap<>(); 29 List<String> hobbys = new ArrayList<>(); 30 hobbys.add("吃饭"); 31 hobbys.add("睡觉"); 32 hobbys.add("吃鸡"); 33 map.put("爱好", hobbys); 34 dbObject.put("hobby", map); 35 listdbo.add(dbObject); 36 37 dbObject = new BasicDBObject(); 38 dbObject.put("name", "老张"); 39 dbObject.put("age", 52); 40 dbObject.put("job", "快递员"); 41 dbObject.put("remark", new BasicDBObject("address", "广东省深圳市").append("street", "深南大道888号")); 42 listdbo.add(dbObject); 43 44 dbCollection.insert(listdbo); 45 } 46 47 /** 48 * json转对象后执行新增 49 * @param dbCollection 50 */ 51 public static void addByJson(DBCollection dbCollection){ 52 String json = "{ \"name\" : \"王五\" , \"age\" : 66 , \"job\" : \"快递员\" , \"remark\" : { \"address\" : \"广东省深圳市\" , \"street\" : \"深南大道888号\"}}"; 53 DBObject dbObject = (DBObject)JSON.parse(json); 54 dbCollection.insert(dbObject); 55 }
方法调用以及运行结果
1 //连接mongoDB,并打开数据库 2 DBCollection dbCollection = MongDBUtile.getInstance(HOST,PORT).getDBCollection(DB_NAME, DBCOLLECTION_NAME); 3 4 addOne(dbCollection); 5 addList(dbCollection); 6 addByJson(dbCollection);
1.2 查询
1 /** 2 * 条件查询:name 为 张三 3 * @param dbCollection 4 */ 5 public static void queryOne(DBCollection dbCollection){ 6 DBObject result = dbCollection.findOne(new BasicDBObject("name","张三")); 7 System.out.println(result); 8 } 9 10 /** 11 * 分页查询:跳过前2条后的3条数据 12 * @param dbCollection 13 */ 14 public static void queryPage(DBCollection dbCollection){ 15 DBCursor cursor = dbCollection.find().skip(2).limit(3); 16 //遍历输出结果 17 while (cursor.hasNext()) { 18 System.out.println(cursor.next()); 19 } 20 } 21 /** 22 * 范围查询:第3条 到 第5条 之间的记录 23 * @param dbCollection 24 * 大于 - $gt 25 * 小于 - $lt 26 * 大于等于 - $gte 27 * 小于等于 - $lte 28 */ 29 public static void queryRange(DBCollection dbCollection) { 30 DBObject range = new BasicDBObject(); 31 range.put("$gte", 28); 32 range.put("$lte", 32); 33 34 DBObject dbObject = new BasicDBObject(); 35 dbObject.put("age", range); 36 DBCursor cursor = dbCollection.find(dbObject); 37 while (cursor.hasNext()) { 38 System.out.println(cursor.next()); 39 } 40 } 41 42 /**' 43 *查询出全部的 记录 44 * @param dbCollection 45 */ 46 public static void queryList(DBCollection dbCollection) { 47 DBCursor cursor = dbCollection.find(); 48 while(cursor.hasNext()){ 49 System.out.println(cursor.next()); 50 } 51 }
方法调用以及运行结果
1 //连接mongoDB,并打开数据库 2 DBCollection dbCollection = MongDBUtile.getInstance(HOST,PORT).getDBCollection(DB_NAME, DBCOLLECTION_NAME); 3 System.out.println("条件查询:name 为 张三"); 4 queryOne(dbCollection); 5 System.out.println("跳过前2条后的3条数据"); 6 queryPage(dbCollection); 7 System.out.println("age在50到52之间的记录"); 8 queryRange(dbCollection); 9 System.out.println("查询出全部的记录"); 10 queryList(dbCollection); 11 12 13 *******************************运行结果******************************* 14 15 条件查询:name 为 张三 16 { "_id" : { "$oid" : "5a50b3d6e6fbe9e658745f04"} , "name" : "张三" , "age" : 45 , "sex" : "男" , "address" : { "postCode" : 100000 , "street" : "深南大道888号" , "city" : "深圳"}} 17 跳过前2条后的3条数据 18 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d5"} , "hobby" : { "爱好" : [ "吃饭" , "睡觉" , "吃鸡"]}} 19 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d6"} , "name" : "老张" , "age" : 52 , "job" : "快递员" , "remark" : { "address" : "广东省深圳市" , "street" : "深南大道888号"}} 20 age在50到52之间的记录 21 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d6"} , "name" : "老张" , "age" : 52 , "job" : "快递员" , "remark" : { "address" : "广东省深圳市" , "street" : "深南大道888号"}} 22 查询出全部的记录 23 { "_id" : { "$oid" : "5a50b3d6e6fbe9e658745f04"} , "name" : "张三" , "age" : 45 , "sex" : "男" , "address" : { "postCode" : 100000 , "street" : "深南大道888号" , "city" : "深圳"}} 24 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d4"} , "name" : "老王" , "remark" : [ "老王1" , "老王2"]} 25 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d5"} , "hobby" : { "爱好" : [ "吃饭" , "睡觉" , "吃鸡"]}} 26 { "_id" : { "$oid" : "5a50b41ae6fb51a28bf2b2d6"} , "name" : "老张" , "age" : 52 , "job" : "快递员" , "remark" : { "address" : "广东省深圳市" , "street" : "深南大道888号"}}
1.3 更新
/** * 修改指定记录 * @param dbCollection */ public static void updateOne(DBCollection dbCollection) { // 先根据id查询将这条记录查询出来 DBObject qryResult = dbCollection.findOne(new ObjectId("5a50b768e6fbda046406b255")); // 修改指定的值 qryResult.put("age", 55); DBObject oldDBObject = new BasicDBObject(); oldDBObject.put("_id", new ObjectId("5a50b768e6fbda046406b255")); dbCollection.update(oldDBObject, qryResult); } /** * 修改多条记录 * @param dbCollection */ public static void updateMulti(DBCollection dbCollection) { DBObject newDBObject = new BasicDBObject(); newDBObject.put("name", "张三"); newDBObject.put("address", "广东深圳"); newDBObject.put("remark", "张三是一个man"); DBObject oldDBObject = new BasicDBObject(); oldDBObject.put("name", "张三"); // 需要加上这个 DBObject upsertValue = new BasicDBObject("$set", newDBObject); // 后面的两个参数:1.若所更新的数据没有,则插入 ; 2、同时更新多个符合条件的文档(collection) dbCollection.update(oldDBObject, upsertValue, true, true); }
方法调用以及运行结果
1.4 删除
1 /** 2 *删除第一个 3 * @param dbCollection 4 */ 5 public static void deleteFirst(DBCollection dbCollection){ 6 DBObject dbObject = dbCollection.findOne(); 7 dbCollection.remove(dbObject); 8 } 9 10 /** 11 * 删除指定的一条记录 12 * @param dbCollection 13 */ 14 public static void deleteOne(DBCollection dbCollection){ 15 DBObject dbObject = new BasicDBObject(); 16 dbObject.put("_id", new ObjectId("5a50b41ae6fb51a28bf2b2d4")); 17 dbCollection.remove(dbObject); 18 } 19 20 /** 21 * 删除多条记录 22 * 例如:select * from tb where name in('12','34') 23 * @param dbCollection25 */ 26 public static void deleteByIn(DBCollection dbCollection) { 27 List<String> list = new ArrayList<String>(); 28 list.add("老张"); 29 list.add("老王"); 30 list.add("张三"); 31 DBObject dbObject = new BasicDBObject("$in", list); 32 33 DBObject delObject = new BasicDBObject(); 34 delObject.put("name", dbObject); 35 dbCollection.remove(delObject); 36 } 37 38 /** 39 * 删除全部的记录 40 * @param dbCollection 41 */ 42 public static void deleteAll(DBCollection dbCollection){ 43 DBCursor cursor = dbCollection.find(); 44 while(cursor.hasNext()){ 45 dbCollection.remove(cursor.next()); 46 } 47 }
stay hungry, stay foolish