该文章只适合于初学者,里面的代码很简单,也多需要优化完善的地方,就是为了让初学者少走弯路,起到借鉴的作用。
需要引用的包:
junit
junit
4.8.1
test
org.jmock
jmock-junit4
2.8.1
org.jmock
jmock
2.8.1
org.jmock
jmock-legacy
2.8.1
org.mongodb
mongo-java-driver
3.1.0
首先,我们拿一个用户来进行操作:
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 addressLists =new ArrayList();
private static List credentialsLists = new ArrayList();
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 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 collection = getUserCollection();
FindIterable 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 collection = getUserCollection();
//方法一
/*MongoCursor 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 userCollection = getUserCollection();
userCollection.insertOne(user.toBasicDBObject());
System.out.println("================================================================");
}
/**
* 更新用户信息
* @param user
*/
public static void update(User user)
{
System.out.println("更新用户信息:" + user.toString());
MongoCollection userCollection = getUserCollection();
userCollection.updateMany(new Document().append("name", user.getName()), user.toBasicDBObject());
System.out.println("================================================================");
}
/**
* 增加用户更新次数
* @param userName 用户名
*/
public static void incUserUpdateTimes(String userName)
{
MongoCollection 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 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 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 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 userMap = (Map) 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 cursor = userCollection.find(query).iterator();
while(cursor.hasNext())
{
Document document = cursor.next();
Map userMap = (Map) 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 ageList)
{
MongoCollection userCollection = getUserCollection();
BasicDBObject query =new BasicDBObject();
query.put("age", new BasicDBObject("$in", ageList));
FindIterable cursor = userCollection.find(query);
while(cursor.iterator().hasNext())
{
System.out.println(cursor.iterator().next());
}
}
public static void queryUserByGreatThanAge(int age)
{
MongoCollection userCollection = getUserCollection();
BasicDBObject query =new BasicDBObject();
query.put("age", new BasicDBObject("$gt", age));
FindIterable cursor = userCollection.find(query);
while(cursor.iterator().hasNext())
{
System.out.println(cursor.iterator().next());
}
}
public static void queryUserByLessThanAge(int age)
{
MongoCollection userCollection = getUserCollection();
BasicDBObject query =new BasicDBObject();
query.put("age", new BasicDBObject("$lt", age));
FindIterable cursor = userCollection.find(query);
while(cursor.iterator().hasNext())
{
System.out.println(cursor.iterator().next());
}
}
public static void queryUserNotEquireAge(int age)
{
MongoCollection userCollection = getUserCollection();
BasicDBObject query =new BasicDBObject();
query.put("age", new BasicDBObject("$ne", age));
FindIterable cursor = userCollection.find(query);
while(cursor.iterator().hasNext())
{
System.out.println(cursor.iterator().next());
}
}
public static void deleteUserByName(String userName)
{
MongoCollection userCollection = getUserCollection();
BasicDBObject document =new BasicDBObject();
document.put("name", userName);
userCollection.deleteMany(document);
}
public static void deleteUserByNameList(List nameList)
{
MongoCollection 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 collection = null;
List foundDocument = null;
collection = database.getCollection("person");
foundDocument = collection.find().into(
new ArrayList());
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");
}
}