首页 > 数据库 >mongodb 实例

mongodb 实例

时间:2023-05-29 12:35:47浏览次数:53  
标签:mongodb System collection 实例 println new mongoClient out


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 {
			// 连接到 mongodb 服务
			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();
			
			// 连接到数据库
			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 {  
            //连接到MongoDB服务,如果是远程连接可以替换“localhost”为服务器所在IP地址  
            //ServerAddress()两个参数分别为 服务器地址 和 端口  
            ServerAddress serverAddress = new ServerAddress("localhost", 27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);
              
            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
            MongoCredential credential = MongoCredential.createScramSha1Credential(username, "databaseName", password.toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);
              
            //通过连接认证获取MongoDB连接  
            MongoClient mongoClient = new MongoClient(addrs, credentials);
              
            //连接到数据库  
            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{   
			// 连接到 mongodb 服务
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
 
			// 连接到数据库
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
			mongoDatabase.createCollection("mycol");
			System.out.println("集合创建成功");
 
			//Get A List of Collections
			for (String name : mongoDatabase.listCollectionNames()) {
			    System.out.println(name);
			}
			
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("集合 mycol 选择成功");
			
			// 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{   
			// 连接到 mongodb 服务
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// 连接到数据库
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");

			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("集合 mycol 选择成功");
			//插入文档  
			/** 
			 * 1. 创建文档 org.bson.Document 参数为key-value的格式 
			 * 2. 创建文档集合List<Document> 
			 * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 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("文档插入成功");
			
			mongoClient.close();
		} catch(Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
	}
	
	public static void find() {
		try{   
			// 连接到 mongodb 服务
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// 连接到数据库
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
	          
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("集合 mycol 选择成功,count=" + collection.count());
	          
			//检索所有文档  
			/** 
			 * 1. 获取迭代器FindIterable<Document> 
			 * 2. 获取游标MongoCursor<Document> 
			 * 3. 通过游标遍历检索出的文档集合 
			 */  
			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{   
			// 连接到 mongodb 服务
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	          
			// 连接到数据库
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");
	          
			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("集合 mycol 选择成功");
	          
			//更新文档   将文档中likes=100的文档修改为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)));
			
			//更新文档   将文档中likes=100的文档的likes 增加50
			collection.updateMany(Filters.eq("likes", 100), new Document("$inc", new Document("likes", 50)));
			
			//检索查看结果  
			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{   
			// 连接到 mongodb 服务
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

			// 连接到数据库
			MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");  
			System.out.println("Connect to database successfully");

			MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
			System.out.println("集合 mycol 选择成功");

			//删除符合条件的第一个文档  
			//collection.deleteOne(Filters.eq("likes", 200));
			//删除所有符合条件的文档  
			collection.deleteMany (Filters.eq("likes", 200));
			//检索查看结果  
			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) {
	}
}

 

 

标签:mongodb,System,collection,实例,println,new,mongoClient,out
From: https://blog.51cto.com/u_16131764/6370067

相关文章

  • Spider理论系列--MongoDB(二)
    NoSQLMongodb下载mongodb的版本,两点注意根据业界规则,偶数为稳定版,如1.6.X,奇数为开发版,如1.7.X32bit的mongodb最大只能存放2G的数据,64bit就没有限制性能BSON格式的编码和解码都是非常快速的。它使用了C风格的数据表现形式,这样在各种语言中都可以高效地使用。NoSQL(NoSQL=NotOnly......
  • WEB漏洞—SQL注入之Oracle,MongoDB等注入
     1.明确注入数据库类型、权限2.明确提交方法、参数类型等高权限可以执行文件读取,低权限就老老实实获取数据,最终目的都是获取网站权限 常见数据库类型mysql,access,mssql,mongoDB,postgresql,sqlite,oracle,sybase等1、Access注入Access与mysql结构,除access之外,其他数据库结......
  • 掌握使用类方法、实例方法时的几点注意事项
    packageitheima;publicclassTest{publicstaticvoidmain(String[]args){//掌握使用类方法、实例方法时的几点注意事项//1.类方法中可以直接访问类的成员,不可以直接访问实例成员//2.实例方法中既可以直接访问类成员,也可以直接访问实例......
  • 深入分析:矩阵梯度类实例研究
    写在前面本文主要用于围绕矩阵类求梯度等问题进行证明与分析,由于笔者的数理基础浅薄,下面的证明过程若存在错误,欢迎评论指正。矩阵梯度的通用方法:先将矩阵写成微分形式,\(df=tr(GdX)\),然后得到$\nablaf=G^T$案例1\(\begin{array}{ll}\min_{U}&\dfrac{1}{2}\left\|\boldsymbol{......
  • MongoDB基本操作记录
    MongoDB基本操作记录连接Mongo:mongo--host127.0.0.1--port27017-uroot-p123456显示数据库列表:showdbs选择数据库:useCX_tb显示所有表名:db.getCollectionNames()删表:db.xxx.drop()显示帮助:db.xxx.help()插入一条数据:db.xxx.insert({"id":"1","add_time":&q......
  • js原型prototype(实例构造函数的属性) __proto__(实例对象的属性) constructor(实例
    functionPerson(name,age){this.name=namethis.age=age}Person.prototype.sayHi=function(){//原型是公共方法解决构造函数new对象公共属性和方法的内存浪费console.log(this.name+'sayhi!!')}constp1=newPerson('aa',12)constp2=new......
  • WPF入门实例 WPF完整例子 WPF DEMO WPF学习完整例子 WPF实战例子 WPF sql实例应用 WPF
    WPF和WinForms都是用于创建Windows桌面应用程序的开发框架,它们有一些相似之处,但也有很多不同之处。在开发速度方面,这取决于具体情况。如果您熟悉WinForms开发并且正在开发简单的界面应用程序,则可能会比使用WPF更快速地完成任务。然而,在设计和实现复杂的用户界面时,WPF可......
  • Java大文件分片上传/多线程上传实例解析
    ​ javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1. 通过form表单向后端发送请求         <formid="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="pos......
  • Struts2实例
    <%@pagelanguage="java"contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%><%@taglibprefix="s"uri="/struts-tags"%><!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitio......
  • arduino esp32 ds18b20 实例代码
    #include<OneWire.h>#include<DallasTemperature.h>//引脚定义#defineONE_WIRE_BUS15//库引用实例OneWireoneWire(ONE_WIRE_BUS);DallasTemperaturesensors(&oneWire);voidsetup(void){Serial.begin(9600);sensors.begin();}voidloop(vo......