import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
public class MongoDBExample {
public static void main(String[] args) {
//用户名
String username = "";
//数据库
String databaseName = "";
//密码
String password = "";
//连接地址
String host = "";
//端口
int port = 8030;
// 创建MongoCredential对象
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
// 创建MongoClientOptions对象
MongoClientOptions options = MongoClientOptions.builder()
.retryWrites(true)
.build();
// 创建MongoClient实例
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), credential, options);
//访问database
MongoDatabase memberInfoDatabase = mongoClient.getDatabase("MemberInfo");
//访问collection
MongoCollection<Document> goldMemberCollection = memberInfoDatabase.getCollection("gold_member");
//创建collection
memberInfoDatabase.createCollection("testCollection", new CreateCollectionOptions().sizeInBytes(200000));
//插入数据
Document doc0 = new Document("name", "万三")
.append("age", 23)
.append("sex", "male");
Document doc1 = new Document("name", "刘亚")
.append("age", 42)
.append("sex", "male");
Document doc2 = new Document("name", "王莹")
.append("age", 22)
.append("sex", "female");
List<Document> documents = new ArrayList<>();
documents.add(doc0);
documents.add(doc1);
documents.add(doc2);
goldMemberCollection.insertMany(documents);
//删除数据
goldMemberCollection.deleteOne(eq("name", "刘亚"));
//删除表
MongoCollection<Document> collection = memberInfoDatabase.getCollection("test");
collection.drop();
//读数据
MongoCursor<String> cursor = (MongoCursor<String>) goldMemberCollection.find();
while (cursor.hasNext()) {
Object result = cursor.next();
}
cursor.close();
//带过滤条件的查询
MongoCursor<String> cursorCondition = (MongoCursor<String>)goldMemberCollection.find(
new Document("name","zhangsan")
.append("age", 5));
while (cursorCondition.hasNext()) {
Object result = cursorCondition.next();
}
cursorCondition.close();
//运行命令
MongoClient mongoClientShell = (MongoClient) MongoClients.create();
MongoDatabase database = mongoClientShell.getDatabase("MemberInfo");
Document buildInfoResults = database.runCommand(new Document("buildInfo", 1));
System.out.println(buildInfoResults.toJson());
Document collStatsResults = database.runCommand(new Document("collStats", "restaurants"));
System.out.println(collStatsResults.toJson());
//创建索引
MongoCollection<Document> collectionTest = memberInfoDatabase.getCollection("gold_member");
collectionTest.createIndex(Indexes.ascending("age"));
}
}