在使用客户端操作之前,需要创建用户:
db.createUser({
user:"hello",
pwd:"test1234",
roles:[{
role:"readWrite",//读写权限
db:"test"
}]
});
指定dbpath,logpath,并启用auth登录方式。
mongod --dbpath=/var/lib/mongo --logpath=/var/log/mongodb/mongod.log --logappend --auth
import org.bson.Document;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
public class MongoDBCase {
public static final String URI ="mongodb://hello:test1234@192.168.1.107:27017/test";
/**
* 查询出所有的集合
*/
@Test
public void connectionMongoDB() {
MongoClientURI uri = new MongoClientURI(URI);
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("test");
MongoCursor<?> cursor = db.listCollectionNames().iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
client.close();
}
/**
* 新增数据
*/
@Test
public void addData() {
MongoClientURI uri = new MongoClientURI(URI);
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("newuserlist");
if (collection == null) {
db.createCollection("newuserlist");
collection = db.getCollection("newuserlist");
}
Document document = new Document("name", "eve").append("age", 24);
collection.insertOne(document);
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
Document obj = (Document) cursor.next();
System.out.println(obj.get("name"));
}
client.close();
}
/**
* 更新数据
*/
@Test
public void updateData() {
MongoClientURI uri = new MongoClientURI(URI);
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("newuserlist");
BasicDBObject obj = new BasicDBObject().append("name", "eve");
BasicDBObject updateObj = new BasicDBObject().append("$set", new BasicDBObject("name", "evetest"));
UpdateResult result = collection.updateOne(obj, updateObj);
System.out.println("更新的条数:" + result.getMatchedCount());
client.close();
}
/**
* 删除数据
*/
@Test
public void deleteData() {
MongoClientURI uri = new MongoClientURI(URI);
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("newuserlist");
BasicDBObject obj = new BasicDBObject().append("name", "evetest");
DeleteResult result = collection.deleteOne(obj);
System.out.println("删除的条数:" + result.getDeletedCount());
client.close();
}
}