mongodb 3.x for java

1.java 连接 mongodb
获取驱动包


maven 地址:
<dependencies>
    <dependency>
        <groupId>org.mongodbgroupId>
        <artifactId>mongodb-driverartifactId>
        <version>3.2.2version>
    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 collection = db.getCollection("test.coll");
        List foundDocument = collection.find().into(new ArrayList());
        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 collection=db.getCollection("test");
        List foundDocument=collection.find().into(new ArrayList());
        System.out.println(foundDocument);
    }

你可能感兴趣的:(mongoDB,mongodb)