Java操作MongoDB:连接&增&删&改&查
1.连接
①方式一
MongoClientOptions.Builder builder = MongoClientOptions.builder(); //可以通过builder做各种详细配置
MongoClientOptions myOptions = builder.build();
ArrayList<ServerAddress> serverAddressList = new ArrayList();
ServerAddress record = new ServerAddress("localhost", 27017); //IP、端口
serverAddressList.add(record);
//用户名、默认库名、密码
MongoCredential credential = MongoCredential.createCredential("testUser", "test", "testPwd".toCharArray());
MongoClient mongoClient = new MongoClient(serverAddressList, credential, myOptions);
②方式二
//用户名、密码、IP、端口、默认库名
String sURI = String.format("mongodb://%s:%s@%s:%d/%s", "testUser", "testPwd", "localhost", 27017, "test");
MongoClient mongoClient = new MongoClient(new MongoClientURI(sURI));
③方式三(没开启权限验证模式时可使用)
//不使用用户名和密码直接进行登陆(方便初学者,避免过于复杂的设置)
MongoClient mongoClient = new MongoClient("localhost", 27017);
2.中间步骤(创建一个collection存放数据,相当于表table)
MongoDatabase dbTest = mongoClient.getDatabase("test");
//如果不存在,则增加collection
MongoCollection<Document> collection = dbTest.getCollection("test_collection");
if (collection == null) {
dbTest.createCollection("test_collection");
}
3.insert
//insert 增加数据
Document doc = new Document();
doc.append("Name", "name1");
doc.append("Age", 20);
//collection.insertOne(doc); //增加一条数据
//增加多条数据
Document doc2 = new Document();
doc2.append("Name", "name2");
doc2.append("Age", 30);
ArrayList dataList = new ArrayList();
dataList.add(doc);
dataList.add(doc2);
collection.insertMany(dataList);
4.delete
//delete 删除数据
BasicDBObject delSql = new BasicDBObject("Name", "name1");
collection.findOneAndDelete(delSql); //删除一条
//collection.deleteMany(delSql); //删除多条
5.update
//update 修改数据
BasicDBObject updateOldSql = new BasicDBObject("Name", "name2");
//更新一条数据
BasicDBObject updateNewOneSql = new BasicDBObject("$set", new BasicDBObject("Name", "name1"));
//collection.updateOne(updateOldSql,updateNewOneSql);
//更新多条数据
BasicDBObject updateNewManySql = new BasicDBObject("$set", new BasicDBObject("Name", "name1").append("Age",66)); //修改多个字段
collection.updateMany(updateOldSql, updateNewManySql);
6.query
//查询数据
BasicDBObject querySql = new BasicDBObject("Name", "name1");
FindIterable<Document> queryRst = collection.find(querySql); //这里可以做sort和filter等操作
MongoCursor<Document> cursor = queryRst.iterator();
while (cursor.hasNext()){
System.out.println(cursor.next());//输出每一行数据
}
以上。