Mongo3.4.7与java1.8结合测试代码

Posted 古月今犹在

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongo3.4.7与java1.8结合测试代码相关的知识,希望对你有一定的参考价值。

1.下载mongo-java-driver-3.5.0.jar驱动并引入测试项目中。

2.代码如下:

package com.zzw.mongodb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.bson.Document;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MapReduceCommand;
import com.mongodb.MapReduceOutput;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MapReduceIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;

public class Test 

	public static void main(String[] args) 
		// TODO Auto-generated method stub	

		//插入
		//insert();
		
		//查询
		query();
		
		//更新
		//update();
		
		//删除
		//delete();
		
	
	
	//有密码连接
	public static MongoDatabase connect1()
        	//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址  
       		//ServerAddress()两个参数分别为 服务器地址 和 端口  
       		ServerAddress serverAddress = new ServerAddress("localhost",27017);  
        	List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
        	addrs.add(serverAddress);  
          
        	//参数: 用户名 数据库名称 密码  
        	MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());  
        	List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
        	credentials.add(credential);  
          
        	//通过连接认证获取MongoDB连接  
        	MongoClient mongoClient = new MongoClient(addrs,credentials);
        	//参数:Collections名称
        	MongoDatabase db = mongoClient.getDatabase("databaseName");
		return db;  
	
	
	//无密码连接
	public static MongoDatabase connect()
		//连接到mongo数据库
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		//获取某一数据库
		MongoDatabase db = mongoClient.getDatabase("test");
		return db;
	
	//插入
	public static void insert()
		//连接到数据库
		MongoDatabase db = connect();
		//获取某一集合	
		MongoCollection<Document> collection = db.getCollection("user");
		//时间格式
		SimpleDateFormat s=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Calendar cal=Calendar.getInstance();
		//插入单个文档
		Document doc = new Document();
		doc.put("name", "zhangsan");
		doc.put("age", 5);
		doc.put("sex", "男");
		doc.put("time", s.format(cal.getTime()));
		collection.insertOne(doc);
		//插入多个文档
		List<Document> docs = new LinkedList<Document>();
		for(int i=0; i<25; i++)
		    Document doc1 = new Document();
		    doc1.put("name", "zhangsan"+(i+1));
		    doc1.put("age", 6+i);
		    if(i % 2 == 0)
				doc1.put("sex", "男");
		    
		    else
				doc1.put("sex", "女");
		    
			doc1.put("time", s.format(cal.getTime()));
		    docs.add(doc1);
		
		collection.insertMany(docs);
		System.out.println("插入成功");
	
	
	//更新
	public static void update()
		//连接到数据库
		MongoDatabase db = connect();
		//获取某一集合	
		MongoCollection<Document> collection = db.getCollection("user");
		//更新全部。更新单个使用collection.updateOne(arg0, arg1)方法
		collection.updateMany(Filters.gt("age",4),new Document("$set",new Document("time","2017/08/24 19:51:48")));
        //检索查看结果  
        FindIterable<Document> findIterable = collection.find();  
        MongoCursor<Document> mongoCursor = findIterable.iterator();  
        while(mongoCursor.hasNext())  
           System.out.println(mongoCursor.next());  
          
        System.out.println("更新成功");
	
	
	//删除
	public static void delete()
		//连接到数据库
		MongoDatabase db = connect();
		//获取某一集合	
		MongoCollection<Document> collection = db.getCollection("user");
        //删除符合条件的第一个文档  
        collection.deleteOne(Filters.gt("age", 4));  
        //删除所有符合条件的文档  
        collection.deleteMany (Filters.gt("age", 4));  
        System.out.println("删除成功");
	
	
	//查询
	public static void query()
		//连接到mongo数据库
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		//获取某一数据库
		MongoDatabase db = mongoClient.getDatabase("test");
		//获取某一集合	
		MongoCollection<Document> collection = db.getCollection("user");
		//输出集合内所有元素
		FindIterable<Document> documents = collection.find();
		for (Document document : documents) 
		    System.out.println(document);
		
		//count()函数可以加 条件,参数形式可以是document或Filters
		long cnt=collection.count();
		System.out.println("共有"+cnt+"条记录");
		
	
		//查找所有name = zhangsan的document
		//Document query1 = new Document("name", "zhangsan");
		//FindIterable<Document> documents1 = collection.find(query1);
		//使用filter查询 :eq ne lt gt lte gte and or in
		FindIterable<Document> documents1 = collection.find(Filters.eq("name", "zhangsan"));
		for (Document d : documents1) 
		    System.out.println(d.toJson());
		
		
		//and 查询
		//Document query2 = new Document("age", new Document("$lt", 25)).append("name", "zhangsan");
		//FindIterable<Document> documents2 = collection.find(query2);  
		FindIterable<Document> documents2 = collection.find(Filters.and(Filters.eq("name", "zhangsan"),Filters.lt("age", 25)));
		for (Document d : documents2) 
		    System.out.println(d.toJson());
		
		
		//or 查询
		//Document query3 = new Document("$or", Arrays.asList(new Document("name", "zhangsan"), new Document("name", "zhangsan1")));
		//FindIterable<Document> documents3 = collection.find(query3);
		FindIterable<Document> documents3 = collection.find(Filters.or(Filters.eq("name", "zhangsan"),Filters.lt("name", "zhangsan1")));
		for (Document d : documents3) 
		    System.out.println(d.toJson());
		

		//between and 查询
		Document query4 = new Document("age", new Document("$lt", 23).append("$gt", 20));
		FindIterable<Document> documents4 = collection.find(query4);    
		for (Document d : documents4) 
		    System.out.println(d.toJson());
		
		
		FindIterable<Document> documents5 = collection.find(Filters.in("age", Arrays.asList(16,18,20)));
		for (Document d : documents5) 
		    System.out.println(d.toJson());
		
		
		//按name升序,name相同的按age降序
		FindIterable<Document> documents6 = collection.find().sort(Sorts.orderBy(Sorts.ascending("name"), Sorts.descending("age")));
		for (Document d : documents6) 
		    System.out.println(d.toJson());
				
		
		//skip()跳过,limit()限制,常用于分页显示。跳过前5条(0-4),返回(5-9)共5条。
		FindIterable<Document> documents7 = collection.find().sort(Sorts.descending("age")).skip(5).limit(5);
		for (Document d : documents7) 
		    System.out.println(d.toJson());
				
		
		System.out.println("ssss");
		//distinct:去重   
		DistinctIterable<String> name = collection.distinct("name", String.class);
		MongoCursor<Integer> c = collection.distinct("age",Integer.class).iterator();
		for (String s : name) 
		    System.out.println(s);
		
		
		//沒有条件
		AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
				new Document("$project", new Document("name", 1).append("_id", 0).append("age", 1).append("sex", 1).append("time", 1))
				,new Document("$group", new Document("_id", "$time").append("avg", new Document("$avg", "$age")).append("first", new Document("$first", "$name")))
				));

		for (Document document : aggregate) 
		    System.out.println(document.toJson());
		
		
		//加入条件
		System.out.println("加入条件后聚合:");
		AggregateIterable<Document> aggregate1 = collection.aggregate(Arrays.asList(
				new Document("$project", new Document("name", 1).append("_id", 0).append("age", 1).append("sex", 1).append("time", 1))
				,new Document("$match", new Document("age",new Document("$lt", 20).append("$gt", 7)))
				,new Document("$group", new Document("_id", "$time").append("avg", new Document("$avg", "$age")).append("first", new Document("$first", "$name")))
				));
		for (Document document : aggregate1) 
		    System.out.println(document.toJson());
		 
		
		//map reduce
		String map = "function()  "+   
	             "var category; " +    
	             "if ( this.age >= 18 ) "+    
	             "category = '青年'; " +  
	             "else " +  
	             "category = '少年'; "+    
	             "emit(category, name: this.name);";  
	     
	   String reduce = "function(key, values)  " +  
	                            "var sum = 0; " +  
	                            "values.forEach(function(doc)  " +  
	                            "sum += 1; "+  
	                            "); " +  
	                            "return count: sum; ";  
	   
	   
	   MapReduceIterable<Document> mr=collection.mapReduce(map, reduce);
	   for (Document o : mr)   
		    System.out.println(o.toJson());  
		     
	





以上是关于Mongo3.4.7与java1.8结合测试代码的主要内容,如果未能解决你的问题,请参考以下文章

Java1.8函数式接口编程结合泛型简单使用案例demo

Mac + Appium + Java1.8学习之Android模拟器自动化测试脚本开发以及简易例子

Gradle - 源代码和测试的不同 JDK 版本

Mac + Appium + Java1.8学习之IOS自动化环境安装配置以及简单测试用例编写(模拟器真机)

java1.8新特性

java1.8函数式编程概念