1.java 连接 mongodb
获取驱动包
maven 地址:
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.2.2</version>
</dependency>
</dependencies>
未启动安全检查模式:
private static void noAuth() {
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017", MongoClientOptions.builder().cursorFinalizerEnabled(false));
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("test.coll");
List<Document> foundDocument = collection.find().into(new ArrayList<Document>());
System.out.println(foundDocument);
}
启动安全检查:
private static void auth() {
MongoCredential credential = MongoCredential.createCredential("mxmx", "test", "mxmx".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential));
MongoDatabase db=mongoClient.getDatabase("test");
MongoCollection<Document> collection=db.getCollection("test");
List<Document> foundDocument=collection.find().into(new ArrayList<Document>());
System.out.println(foundDocument);
}