mongodb instance

package com.jaeson.mongodb;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
//import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.Projections;

public class MongodbTest {

	@SuppressWarnings("unused")
	public static void connectServer() {
		try {
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
			//MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
			//MongoClient mongoClient = new MongoClient(connectionString);
			//MongoClient mongoClient = new MongoClient(
			//	Arrays.asList(new ServerAddress("localhost", 27017),
		    	//		new ServerAddress("localhost", 27018)));
			
			//Get A List of Databases
			for (String name: mongoClient.listDatabaseNames()) {
			    System.out.println(name);
			}
			
			//drop database
			//mongoClient.getDatabase("databaseToBeDropped").drop();
			
			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	@SuppressWarnings("unused")
	public static void connectServer(String username, String password) {
        try {  
            //Connect to the MongoDB service, if it is a remote connection, you can replace "localhost" with the IP address of the server  
            //ServerAddress() The two parameters are the server address and port respectively  
            ServerAddress serverAddress = new ServerAddress("localhost", 27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);
              
            //MongoCredential.createScramSha1Credential() The three parameters are username database name password  
            MongoCredential credential = MongoCredential.createScramSha1Credential(username, "databaseName", password.toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);
              
            //Get MongoDB connection through connection authentication  
            MongoClient mongoClient = new MongoClient(addrs, credentials);
              
            //connect to database  
            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
            System.out.println("Connect to database successfully");
            
            mongoClient.close();
        } catch (Exception e) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }  

	public static void createCollection() {
		try{   
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
 
			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
			mongoDatabase.createCollection("mycol");
			System.out.println("Collection created successfully");
 
			//Get A List of Collections
			for (String name : mongoDatabase.listCollectionNames()) {
			    System.out.println(name);
			}
			
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("Collection mycol selected successfully");
			
			// create an ascending index on the "i" field, 1 = ascending, -1 = descending
			collection.createIndex(new Document("i", 1));
			
			//Get a List of Indexes on a Collection
			for (final Document index : collection.listIndexes()) {
			    System.out.println(index.toJson());
			}
			
			//drop collection
			//collection.dropCollection();
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void insert() {
		try{   
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");

			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("Collection mycol selected successfully");
			//insert document  
			/**
			 * 1. Create document org.bson.Document parameter is key-value format
			 * 2. Create a document collection List<Document>
			 * 3. Insert the document collection into the database collection mongoCollection.insertMany(List<Document>) Inserting a single document can use mongoCollection.insertOne(Document)
			 */
			Document document = new Document("title", "MongoDB").
				append("description", "database").
				append("likes", 100).
				append("by", "Fly");
			List<Document> documents = new ArrayList<Document>();
			documents.add(document);
			collection.insertMany(documents);
			//collection.insertOne(document);
			System.out.println("Document inserted successfully");
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void find() {
		try{   
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
	          
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("Collection mycol selected successfully, count=" + collection.count());
	          
			// retrieve all documents  
			/**
			 * 1. Get the iterator FindIterable<Document>
			 * 2. Get the cursor MongoCursor<Document>
			 * 3. Traverse the retrieved document collection through the cursor
			 */  
			FindIterable<Document> findIterable = collection.find();
			MongoCursor<Document> mongoCursor = findIterable.iterator();
			while (mongoCursor.hasNext()) {
				System.out.println(mongoCursor.next());
			}
			
			List<Document> foundDocument = collection.find().into(new ArrayList<Document>());
			for (Document document : foundDocument) {
				System.out.println(document.toJson());
			}
			
			//find first
			Document myDoc = collection.find(Filters.eq("likes", 100)).first();
			System.out.println(myDoc.toJson());
			
			//find 50 < likes <= 200
			Block<Document> printBlock = new Block<Document>() {
			     @Override
			     public void apply(final Document document) {
			         System.out.println(document.toJson());
			     }
			};
			collection.find(Filters.and(Filters.gt("likes", 50), Filters.lte("likes", 200))).forEach(printBlock);
			
			//sort by likes desc
			myDoc = collection.find(Filters.exists("likes")).sort(Sorts.descending("likes")).first();
			System.out.println(myDoc.toJson());
			
			//exclude the _id field
			myDoc = collection.find().projection(Projections.excludeId()).first();
			System.out.println(myDoc.toJson());

			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void update() {
		try{   
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
	          
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("Collection mycol selected successfully");
	          
			//Update the document Change the document with likes=100 in the document to likes=200
			//collection.updateOne(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
			collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
			
			//Update the document to increase the likes of documents with likes=100 in the document by 50
			collection.updateMany(Filters.eq("likes", 100), new Document("$inc", new Document("likes", 50)));
			
			//Retrieve view result  
			FindIterable<Document> findIterable = collection.find();
			MongoCursor<Document> mongoCursor = findIterable.iterator();
			while (mongoCursor.hasNext()) {
				System.out.println(mongoCursor.next());
			}
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void delete() {
		try{   
			// connect to mongodb service
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");

			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("Collection mycol selected successfully");

			// delete the first document that matches the condition  
			//collection.deleteOne(Filters.eq("likes", 200));
			// delete all eligible documents  
			collection.deleteMany (Filters.eq("likes", 200));
			//Retrieve view result  
			FindIterable<Document> findIterable = collection.find();
			MongoCursor<Document> mongoCursor = findIterable.iterator();
			while (mongoCursor.hasNext()) {
				System.out.println(mongoCursor.next());
			}
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void main(String[] args) {
	}
}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326903020&siteId=291194637