<Dependency> <groupId>Org.mongodb</groupId> <Artifactid>Mongodb-driver</Artifactid> <version>3.2.2</version> </Dependency>
Importjava.util.ArrayList; Importorg.bson.Document;Importjava.util.List; Importcom.mongodb.MongoClient; Importcom.mongodb.MongoCredential; Importcom.mongodb.ServerAddress;Importcom.mongodb.client.MongoCollection;ImportCom.mongodb.client.MongoCursor;Importcom.mongodb.client.MongoDatabase; Importcom.mongodb.client.FindIterable; Public classMongodbapphbasetest { Public Static voidMain (string[] args) {Try { //Connect to a MONGODB service if a remote connection can replace "localhost" with the IP address of the server//serveraddress () Two parameters are server address and port, respectivelyServerAddress serveraddress =NewServerAddress ("1.1.1.1", 27017); List<ServerAddress> Addrs =NewArraylist<serveraddress>(); Addrs.add (serveraddress); //mongocredential.createscramsha1credential () Three parameters are user name database name passwordMongocredential credential = mongocredential.createscramsha1credential ("xxx", "xxx", "xxx". ToCharArray ()); List<MongoCredential> credentials =NewArraylist<mongocredential>(); Credentials.add (credential); //obtaining MongoDB connections through connection authenticationMongoclient mongoclient =Newmongoclient (Addrs, credentials); //connecting to a databaseMongodatabase mongodatabase = Mongoclient.getdatabase ("name"); System.out.println ("Connect to database successfully"); //mongodatabase.createcollection ("xxx");//System.out.println ("collection Creation succeeded");mongocollection<Document> collection = mongodatabase.getcollection ("xxx"); System.out.println ("Set XXX Select Success"); //Retrieving all Documents /*** 1. Get iterator finditerable<document> * 2. Get cursor mongocursor<document> * 3. Iterating through a retrieved collection of documents through a cursor **/finditerable<Document> finditerable =Collection.find (); Mongocursor<Document> Mongocursor =Finditerable.iterator (); intI=0; while(Mongocursor.hasnext ()) {System.out.println (Mongocursor.next ()); I++; } System.out.println ("I=" +i); } Catch(Exception e) {System.err.println (E.getclass (). GetName ()+ ": " +e.getmessage ()); } } }
JAVA API reads data from MongoDB