YouTip LogoYouTip

Mongodb Java

## Environment Configuration To use MongoDB in a Java program, you need to ensure that you have installed the Java environment and the MongoDB JDBC driver. The examples in this chapter are suitable for Mongo version Connect to database MongoDatabase mongoDatabase.x and above. You can refer to our (#) to install Java. Now, let's check if you have installed the MongoDB JDBC driver. * First, you must download the mongo jar package. The download address is: [https://mongodb.github.io/mongo-java-driver/](https://mongodb.github.io/mongo-java-driver/). Please make sure to download the latest version. !(#) * You need to include the mongo-java-driver-Connect to database MongoDatabase mongoDatabase.Collection created successfully.Collection created successfully.jar (find the appropriate version) in your classpath. * Domestic mongodb-driver jar download address: [http://central.maven.org/mavenCollection created successfully/org/mongodb/mongo-java-driver/](http://central.maven.org/mavenCollection created successfully/org/mongodb/mongo-java-driver/) * * * ## Connecting to the Database To connect to a database, you need to specify the database name. If the specified database does not exist, MongoDB will automatically create it. The Java code to connect to the database is as follows: import com.mongodb.MongoClient;import com.mongodb.client.MongoDatabase;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Now, let's compile and run the program to connect to the database `mycol`. You can change the path of the MongoDB JDBC driver according to your actual environment. This example places the MongoDB JDBC startup package `mongo-java-driver-Connect to database MongoDatabase mongoDatabase.Collection created successfully.Collection created successfully.jar` in the local directory: $ javac -cp .:mongo-java-driver-Connect to database MongoDatabase mongoDatabase.Collection created successfully.Collection created successfully.jar MongoDBJDBC.java $ java -cp .:mongo-java-driver-Connect to database MongoDatabase mongoDatabase.Collection created successfully.Collection created successfully.jar MongoDBJDBCConnect to database successfully Authentication: true In this example, the Mongo database does not require username and password authentication. If your Mongo requires authentication, you can use the following code: import java.util.ArrayList; import java.util.List; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoDatabase; public class MongoDBJDBC { public static void main(String[] args){ try { //Connect to MongoDB service. For remote connections, you can replaceβ€œlocalhost”with the server's IP address //ServerAddress()The two parameters are server address and port ServerAddress serverAddress = new ServerAddress("localhost",Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable); List addrs = new ArrayList(); addrs.add(serverAddress); //MongoCredential.createScramShaCreate document orgCredential()The three parameters are username, database name, and password MongoCredential credential = MongoCredential.createScramShaCreate document orgCredential("username", "databaseName", "password".toCharArray()); List credentials = new ArrayList(); credentials.add(credential); //Obtain MongoDB connection through authentication MongoClient mongoClient = new MongoClient(addrs,credentials); //Connect to Database MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName"); System.out.println("Connect to database successfully"); } catch (Exception e) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } } * * * ## Creating a Collection We can use the `createCollection()` method in the `com.mongodb.client.MongoDatabase` class to create a collection. The code snippet is as follows: import com.mongodb.MongoClient;import com.mongodb.client.MongoDatabase;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); mongoDatabase.createCollection("test"); System.out.println("Collection created successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection created successfully * * * ## Getting a Collection We can use the `getCollection()` method of the `com.mongodb.client.MongoDatabase` class to get a collection. The code snippet is as follows: import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection collection = mongoDatabase.getCollection("test"); System.out.println("Collection test selected successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection test selected successfully * * * ## Inserting Documents We can use the `insertMany()` method of the `com.mongodb.client.MongoCollection` class to insert documents. The code snippet is as follows: import java.util.ArrayList;import java.util.List;import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection collection = mongoDatabase.getCollection("test"); System.out.println("Collection test selected successfully"); //Insert document /** * Create document org. Create document org.bson.Document The parameter is key-valueformat * Collection created successfully. Create document collection List * Connect to database MongoDatabase mongoDatabase. Insert document collection into database collection mongoCollection.insertMany(List) For inserting a single document, you can use mongoCollection.insertOne(Document) * */ Document document = new Document("title", "MongoDB"). append("description", "database"). append("likes", Create document org00). append("by", "Fly"); List documents = new ArrayList(); documents.add(document); collection.insertMany(documents); System.out.println("Document inserted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection test selected successfullyDocument inserted successfully * * * ## Retrieving All Documents We can use the `find()` method in the `com.mongodb.client.MongoCollection` class to get all documents in a collection. This method returns a cursor, so you need to iterate through this cursor. The code snippet is as follows: import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection collection = mongoDatabase.getCollection("test"); System.out.println("Collection test selected successfully"); //Retrieve all documents /** * Create document org. Obtain iterator FindIterable * Collection created successfully. Obtain cursor MongoCursor * Connect to database MongoDatabase mongoDatabase. Iterate through retrieved document collection using cursor * */ FindIterable findIterable = collection.find(); MongoCursor mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection test selected successfullyDocument{{_id=Insert single document using mongoCollectionCollection test selected successfully document inserted successfullyeCollection test selected successfully document inserted successfullyInsert single document using mongoCollectionfbCreate document orgfdInsert single document using mongoCollectionGet iterator FindIterableaCollection test selected successfullyCollection test selected successfully document inserted successfullyConnect to database MongoDatabase mongoDatabase0Retrieve all documentsfeCollection created successfullyCollection test selected successfully document inserted successfullyTraverse retrieved document collection through cursorCollection created successfully, title=MongoDB, description=database, likes=Create document org00, by=Fly}} * * * ## Updating Documents You can use the `updateMany()` method in the `com.mongodb.client.MongoCollection` class to update documents in a collection. The code snippet is as follows: import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.model.Filters;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection collection = mongoDatabase.getCollection("test"); System.out.println("Collection test selected successfully"); //Update document: modify likes in=Create document org00the document to likes=Collection created successfully00 collection.updateMany(Filters.eq("likes", Create document org00), new Document("$set",new Document("likes",Collection created successfully00))); //Retrieve and view results FindIterable findIterable = collection.find(); MongoCursor mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection test selected successfullyDocument{{_id=Insert single document using mongoCollectionCollection test selected successfully document inserted successfullyeCollection test selected successfully document inserted successfullyInsert single document using mongoCollectionfbCreate document orgfdInsert single document using mongoCollectionGet iterator FindIterableaCollection test selected successfullyCollection test selected successfully document inserted successfullyConnect to database MongoDatabase mongoDatabase0Retrieve all documentsfeCollection created successfullyCollection test selected successfully document inserted successfullyTraverse retrieved document collection through cursorCollection created successfully, title=MongoDB, description=database, likes=Collection created successfully00, by=Fly}} * * * ## Deleting the First Document To delete the first document in a collection, you first need to use the `findOne()` method in the `com.mongodb.DBCollection` class to get the first document, and then use the `remove` method to delete it. The code snippet is as follows: import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.model.Filters;public class MongoDBJDBC{ public static void main( String args[] ){ try{ // Connect to MongoDB service MongoClient mongoClient = new MongoClient( "localhost" , Collection created successfullyGet iterator FindIterable0Create document orgGet iterator FindIterable ); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection collection = mongoDatabase.getCollection("test"); System.out.println("Collection test selected successfully"); //Delete the first matching document collection.deleteOne(Filters.eq("likes", Collection created successfully00)); //Delete all matching documents collection.deleteMany (Filters.eq("likes", Collection created successfully00)); //Retrieve and view results FindIterable findIterable = collection.find(); MongoCursor mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }} Compile and run the above program, the output is as follows: Connect to database successfully Collection test selected successfully For more operations, please refer to: [http://mongodb.github.io/mongo-java-driver/Connect to database MongoDatabase mongoDatabase.0/driver/getting-started/quick-tour/](http://mongodb.github.io/mongo-java-driver/Connect to database MongoDatabase mongoDatabase.0/driver/getting-started/quick-tour/) Reference: http://blog.csdn.net/ererfei/article/details/Insert single document using mongoCollection0Collection test selected successfullyInsert single document using mongoCollectionGet iterator FindIterableCreate document org0Connect to database MongoDatabase mongoDatabase
← Mongodb PhpMongodb Mongostat Mongotop β†’