1. 需要jar包:
maven依赖:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.4</version>
</dependency>
2.设置db数据库的安全验证机制:
①创建用户
②在开启mongoDB的时候使用安全模式:
3.java代码,实现CRUD。
package mongoDb;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
public class MongoDBUtil {
static MongoClient client;
static DB db;
static DBCollection collection;
static {
try {
// client = new MongoClient("192.168.20.114", 27017);
System.out.println("连接服务器测试.................");
ServerAddress serverAddress = new ServerAddress("192.168.20.114", 27017);
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(serverAddress);
MongoCredential credentials = MongoCredential.createMongoCRCredential("testAdmin", "test",
"123".toCharArray());
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
credentialsList.add(credentials);
client = new MongoClient(seeds, credentialsList);
// (List<ServerAddress> seeds, List<MongoCredential//
db = client.getDB("test");
// db.authenticate("testAdmin", "123".toCharArray());
collection = db.getCollection("user");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void add(DBObject dbObject) {
collection.insert(dbObject);
}
public static void del(DBObject dbObject) {
collection.remove(dbObject);
}
public static void update(DBObject dbObject1, DBObject dbObject2) {
collection.update(dbObject1, dbObject2);
}
public static DBObject queryOneByKey(DBObject dbObject, DBObject keys) {
DBCursor dbCursor = collection.find(dbObject, keys);
if (dbCursor.hasNext()) {
return dbCursor.next();
}
return null;
}
public static java.util.List<DBObject> query(DBObject dbObject) {
DBCursor dbCursor = collection.find(dbObject);
List<DBObject> ret = new ArrayList<DBObject>();
while (dbCursor.hasNext()) {
DBObject dbObject2 = dbCursor.next();
ret.add(dbObject2);
}
return ret;
}
public static void main(String[] args) {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("num", new BasicDBObject("$gt", 0));
List<DBObject> ret = MongoDBUtil.query(dbObject);
for (Iterator<DBObject> it = ret.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}