该文章只适合于初学者,里面的代码很简单,也多需要优化完善的地方,就是为了让初学者少走弯路,起到借鉴的作用。
需要引用的包:
<span style="white-space:pre"> </span><dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-junit4</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-legacy</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.1.0</version> </dependency>
首先,我们拿一个用户来进行操作:
1创建一个User实体对象:
public class User { private String name = null; private int age = -1; private int updateTimes = -1; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getUpdateTimes() { return updateTimes; } public void setUpdateTimes(int updateTimes) { this.updateTimes = updateTimes; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", updateTimes=" + updateTimes + "]"; } public Document toBasicDBObject() { Document user = new Document(); user.put("name", this.name); user.put("age", this.age); user.put("updateTimes", this.updateTimes); return user; } }
public final class MongoDBUtil { private static MongoClient mongoClient = null; private static MongoDatabase database = null; private static ServerAddress serverAddress = null; private static MongoCredential credentials = null; private static List<ServerAddress> addressLists =new ArrayList<ServerAddress>(); private static List<MongoCredential> credentialsLists = new ArrayList<MongoCredential>(); public static void init(){ try{ //mongoClient = new MongoClient("192.168.32.129",27017); serverAddress = new ServerAddress("192.168.32.129",27017); addressLists.add(serverAddress); //credentials = MongoCredential.createCredential("test1", "test", "test1".toCharArray()); credentials = MongoCredential.createMongoCRCredential("test1", "test", "test1".toCharArray()); credentialsLists.add(credentials); mongoClient = new MongoClient(addressLists, credentialsLists); }catch (MongoException e) { System.out.println(e.toString()); } if(null != mongoClient){ database = mongoClient.getDatabase("test"); } } public static MongoClient getMongoClient() { if (null == mongoClient) { init(); } return mongoClient; } /** * 获取database * @return */ public static MongoDatabase getDatabase() { if(null == mongoClient){ init(); } return database; } /** * 获取User Collection * @return */ public static MongoCollection<Document> getUserCollection(){ if(null == database){ database = getDatabase(); } if(null != database){ return database.getCollection("data"); } return null; } /** * 删除所有用户 */ public static void deleteAllUsers(){ System.out.println("删除User Collection中所有数据..."); MongoCollection<Document> collection = getUserCollection(); FindIterable<Document> cursor = collection.find(); while(cursor.iterator().hasNext()){ collection.deleteOne(cursor.iterator().next()); } System.out.println("===================================="); } /** * 查询所有用户 */ public static void queryAllUsers(){ System.out.println("查询User Collection中所有数据:"); MongoCollection<Document> collection = getUserCollection(); //方法一 /*MongoCursor<Document> cur = collection.find().iterator(); try{ while (cur.hasNext()) { System.out.println(cur.next().toJson()); } }catch(Exception e){ System.out.println(e.getMessage()+e); }finally { cur.close(); }*/ //方法二 for (Document cursor : collection.find()) { System.out.println(cursor.toJson()); } System.out.println("================================================================"); } /** * 保存用户信息 * @param user */ public static void saveUser(User user){ System.out.println("保存用户信息:" + user.toString()); MongoCollection<Document> userCollection = getUserCollection(); userCollection.insertOne(user.toBasicDBObject()); System.out.println("================================================================"); } /** * 更新用户信息 * @param user */ public static void update(User user) { System.out.println("更新用户信息:" + user.toString()); MongoCollection<Document> userCollection = getUserCollection(); userCollection.updateMany(new Document().append("name", user.getName()), user.toBasicDBObject()); System.out.println("================================================================"); } /** * 增加用户更新次数 * @param userName 用户名 */ public static void incUserUpdateTimes(String userName) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject newDocument =new BasicDBObject().append("$inc", new BasicDBObject().append("updateTimes", 1)); userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument); } /** * 更新用户名 * @param oldName 旧用户名 * @param newName 新用户名 */ public static void updateUserName(String oldName, String newName) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject newDocument =new BasicDBObject().append("$set", new BasicDBObject().append("name", newName)); userCollection.updateOne(new BasicDBObject().append("name", oldName), newDocument); } /** * 更新User Age * @param userName 用户名 * @param age Age */ public static void updateUserAge(String userName, int age) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject newDocument =new BasicDBObject().append("$set", new BasicDBObject().append("age", age)); userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument); } public static User queryUserByName(String userName) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("name", userName); User user = null; for (Document cursor : userCollection.find(query)) { System.out.println(cursor.toJson()); Map<String, Object> userMap = (Map<String, Object>) cursor; user = new User(); user.setName(String.valueOf(userMap.get("name"))); user.setAge(Integer.valueOf(String.valueOf(userMap.get("age")))); user.setUpdateTimes(Integer.valueOf(String.valueOf(userMap.get("updateTimes")))); System.out.println(user.toString()); } /*MongoCursor<Document> cursor = userCollection.find(query).iterator(); while(cursor.hasNext()) { Document document = cursor.next(); Map<String, Object> userMap = (Map<String, Object>) document; user = new User(); user.setName(String.valueOf(userMap.get("name"))); user.setAge(Integer.valueOf(String.valueOf(userMap.get("age")))); user.setUpdateTimes(Integer.valueOf(String.valueOf(userMap.get("updateTimes")))); System.out.println(user.toString()); }*/ return user; } public static void queryUserByAge(List<Integer> ageList) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("age", new BasicDBObject("$in", ageList)); FindIterable<Document> cursor = userCollection.find(query); while(cursor.iterator().hasNext()) { System.out.println(cursor.iterator().next()); } } public static void queryUserByGreatThanAge(int age) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("age", new BasicDBObject("$gt", age)); FindIterable<Document> cursor = userCollection.find(query); while(cursor.iterator().hasNext()) { System.out.println(cursor.iterator().next()); } } public static void queryUserByLessThanAge(int age) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("age", new BasicDBObject("$lt", age)); FindIterable<Document> cursor = userCollection.find(query); while(cursor.iterator().hasNext()) { System.out.println(cursor.iterator().next()); } } public static void queryUserNotEquireAge(int age) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("age", new BasicDBObject("$ne", age)); FindIterable<Document> cursor = userCollection.find(query); while(cursor.iterator().hasNext()) { System.out.println(cursor.iterator().next()); } } public static void deleteUserByName(String userName) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject document =new BasicDBObject(); document.put("name", userName); userCollection.deleteMany(document); } public static void deleteUserByNameList(List<String> nameList) { MongoCollection<Document> userCollection = getUserCollection(); BasicDBObject query =new BasicDBObject(); query.put("name", new BasicDBObject("$in", nameList)); userCollection.deleteMany(query); } public static void setDatabase(MongoDatabase database) { MongoDBUtil.database = database; } }注意:该工具中只有下面单元测试中的几个方法是成功测试的,其他的还需要自己下面测试,应该也是没问题的。
3最后,单元测试看看效果,是否真的可行:
public class MongoDBTest { public static void main(String[] args) { System.out.println("================================================================"); // 查询所有的Database MongoClient mongoClient = MongoDBUtil.getMongoClient(); System.out.println("查询MongoDB中存在的所有数据库:"); for (ServerAddress name : mongoClient.getAllAddress()) { System.out.println("dbName: " + name); } // 查询DB中所有的Collection(可以理解为像关系型数据库中的Table) MongoDatabase database = MongoDBUtil.getDatabase(); System.out.println("abd="+database.getCollection("abc").toString()); MongoCollection<Document> collection = null; List<Document> foundDocument = null; collection = database.getCollection("person"); foundDocument = collection.find().into( new ArrayList<Document>()); System.out.println(foundDocument); } @Test public void addUsers(){ for(int i=0;i<20000;i++){ User user = new User(); user.setName("user" + i); user.setAge(2); user.setUpdateTimes(0); //保存用户信息 MongoDBUtil.saveUser(user); System.out.println("------------"+i); } } @Test public void deleteAllUsers(){ MongoDBUtil.deleteAllUsers(); } @Test public void queryAllUsers(){ MongoDBUtil.queryAllUsers(); } @Test public void updateUser(){ User user = new User(); user.setName("user19999"); user.setAge(39); user.setUpdateTimes(3); MongoDBUtil.update(user); } @Test public void queryUserByName(){ MongoDBUtil.queryUserByName("user19999"); } }