Mongodb查询

来自ling
跳转至: 导航搜索

文件:Mongodb update.png 文件:Mongodb Criteria.png

/** 
 * MongoDBTest 
 * MongoDB JAVA API的高级查询示例 
 */  
package com.labci.mongodb.test;  
import java.net.UnknownHostException;  
import java.util.Iterator;  
import com.mongodb.BasicDBObject;  
import com.mongodb.DB;  
import com.mongodb.DBCollection;  
import com.mongodb.DBCursor;  
import com.mongodb.DBObject;  
import com.mongodb.Mongo;  
import com.mongodb.MongoException;  
/** 
 * @author Bill Tu(tujiyue/iwtxokhtd) 
 * May 21, 2011[11:33:34 PM] 
 * 
 */  
public class MongoDBAdvancedQuery {  
    private static final String HOST = "192.168.1.86";  
    private static final int PORT = 27017;  
    private static final String USER = "iwtxokhtd";  
    private static final String PASSWORD = "123456";  
    private static final String DB_NAME = "test";  
    private static final String COLLECTION = "data_test";  
    private static Mongo conn=null;  
    private static DB myDB=null;  
    private static DBCollection myCollection=null;  
      
    static{  
        try {  
            conn=new Mongo(HOST,PORT);//建立数据库连接  
            myDB=conn.getDB(DB_NAME);//使用test数据库  
            boolean loginSuccess=myDB.authenticate(USER, PASSWORD.toCharArray());//用户验证  
            if(loginSuccess){  
                myCollection=myDB.getCollection(COLLECTION);  
            }  
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch (MongoException e) {  
            e.printStackTrace();  
        }  
    }  
      
    /** 
     * 查询数据 
     * @param collection “表”名 
     */  
    private static void queryData(DBCollection collection){  
        //count查询  
        System.out.println("表的总记录数为:");  
        System.out.println(collection.find().count());  
        //分页查询  
        DBCursor findAll=collection.find();  
        DBCursor queryByPage=findAll.skip(3).limit(4);  
        printData("从第3条记录起取4条记录为:",queryByPage);  
        //order by操作  
        DBObject orderBy = new BasicDBObject();  
        orderBy.put("userName", -1);//按userName倒序排  
        DBCursor orderByResult=collection.find().sort(orderBy);  
        printData("所有记录按userName倒序排为:",orderByResult);  
          
        // "!=" 和 ">" 操作  
        DBObject notEqual=new BasicDBObject();  
        notEqual.put("$ne", "Bill Tu10");  
          
        DBObject greatThan=new BasicDBObject();  
        greatThan.put("$gt", 7);  
          
        DBObject notEqualAndGreatThan=new BasicDBObject();  
        notEqualAndGreatThan.put("userName", notEqual);  
        notEqualAndGreatThan.put("age", greatThan);  
          
        DBCursor notEqualAndGreatThanResult=collection.find(notEqualAndGreatThan);  
        printData("userName!='Bill Tu10' and age>7的记录为:",notEqualAndGreatThanResult);  
          
        // ">=" 和"<="操作  
        DBObject greatThanEqualAndLessThanEqual=new BasicDBObject();  
        greatThanEqualAndLessThanEqual.put("$gte", 2);  
        greatThanEqualAndLessThanEqual.put("$lte", 7);  
          
        DBObject ageCompare=new BasicDBObject();  
        ageCompare.put("age",greatThanEqualAndLessThanEqual);  
          
        DBCursor compareResult=collection.find(ageCompare);  
        printData("age>=2 and age<=7的记录为:",compareResult);  
          
        // all操作  
        DBObject all=new BasicDBObject();  
        all.put("$all", new Object[]{7,7});  
          
        DBObject rankAll=new BasicDBObject();  
        rankAll.put("rank", all);  
          
        DBCursor rankAllResult=collection.find(rankAll);  
        printData("rank in all(7,7)的记录为:",rankAllResult);  
          
        //not in操作  
        DBObject notIn=new BasicDBObject();  
        notIn.put("$nin", new Object[]{2,3});  
          
        DBObject ageNotIn=new BasicDBObject();  
        ageNotIn.put("age", notIn);  
          
        DBCursor ageNotInResult=collection.find(ageNotIn);  
        printData("age not in (2,3)的记录为:",ageNotInResult);  
          
        //or操作  
        DBObject orGreatThan=new BasicDBObject("$gt",3);  
        DBObject orRankAll=new BasicDBObject("$all",new Object[]{1,1});  
        DBObject ageOrGreatThan=new BasicDBObject();  
        ageOrGreatThan.put("age", orGreatThan);  
        DBObject rankOrAll=new BasicDBObject();  
        rankOrAll.put("rank", orRankAll);  
          
        DBObject orOperation=new BasicDBObject();  
        orOperation.put("$or", new Object[]{ageOrGreatThan,rankOrAll});  
          
        DBCursor orResult=collection.find(orOperation);  
        printData("age>3 or rank in all(1,1)的记录为:",orResult);  
          
        //not or操作  
        DBObject notOrOperation=new BasicDBObject();  
        notOrOperation.put("$nor", new Object[]{ageOrGreatThan,rankOrAll});  
          
        DBCursor notOrResult=collection.find(notOrOperation);  
        printData("not(age>3 or rank in all(1,1))的记录为:",notOrResult);  
          
        //size 操作  
        DBObject size=new BasicDBObject("$size",3);  
        DBObject rankSize=new BasicDBObject();  
        rankSize.put("rank", size);  
          
        DBCursor sizeResult=collection.find(rankSize);  
        printData("rank数组大小为3的记录为:",sizeResult);  
          
        //exists操作  
        DBObject exists=new BasicDBObject("$exists",false);  
        DBObject userNameExists=new BasicDBObject();  
        userNameExists.put("userName", exists);  
          
        DBCursor userNameExistsResult=collection.find(userNameExists);  
        printData("userName exists false的记录为:",userNameExistsResult);  
          
        //mod 取模操作  
        DBObject modArray=new BasicDBObject("$mod",new Object[]{2,0});  
        DBObject ageMod=new BasicDBObject();  
        ageMod.put("age", modArray);  
          
        DBCursor ageModResult=collection.find(ageMod);  
        printData("age%2==0的记录为:",ageModResult);  
          
    }  
      
    /** 
     * 打印结果数据 
     * @param description 结果数据相关描述 
     * @param recordResult 结果集 
     */  
    private static void printData(String description,DBCursor recordResult){  
        System.out.println(description);  
        for(Iterator<DBObject> iter=recordResult.iterator();iter.hasNext();){  
            System.out.println(iter.next());  
        }  
    }  
      
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        queryData(myCollection);  
    }  
}
@Override
	public List<IitDeductionClaimHCompareVo> iitDeductionClaimHCompare(Date start, Date end) {
		if(start == null) {
			start = DateUtil.addMonth(end, -1);
		}
		int startYear = DateUtil.getYear(start);
		int startMonth = DateUtil.getMonth(start);
		int endYear = DateUtil.getYear(end);
		int endMonth = DateUtil.getMonth(end);
		Criteria criteria = Criteria.where("orgId").is(this.getOrgId())
				.and("tenantId").is(this.getTenantId())
				.and("year").in(Arrays.asList(endYear,startYear))
				.and("month").in(Arrays.asList(endMonth,startMonth));
		List<IitDeductionPersonalReport> list = this.mongoDao.query(IitDeductionPersonalReport.class, criteria);
		Map<String,List<IitDeductionPersonalReport>> groupMap = list.stream().collect(Collectors.groupingBy(IitDeductionPersonalReport::getBasePersonalInfoUuid));
		List<IitDeductionClaimHCompareVo> result = new ArrayList<>(list.size());
		groupMap.forEach((k,v) -> {
			IitDeductionPersonalReport startRpt = v.get(0);
			IitDeductionClaimHCompareVo startVo = convertToIitDeductionClaimH2(startRpt.getFullFillingMap());
			if(v.size() > 1) {
				v.sort((t1,t2) -> {
					int a = t1.getYear() * 12 + t1.getMonth();
					int b = t2.getYear() * 12 + t2.getMonth();
					return a == b ? 0 : a > b ? 1 : -1;
				});
				IitDeductionPersonalReport endRpt = v.get(1);
				IitDeductionClaimHCompareVo endVo = convertToIitDeductionClaimH2(endRpt.getFullFillingMap());
				if(endVo.compare(startVo)) {
					endVo.setIitDeductionClaimHUuid(endRpt.getIitDeductionClaimHUuid());
					endVo.setBasePersonalInfoUuid(k);
					endVo.setStaffCode(endRpt.getStaffCode());
					endVo.setPeriodYear(endRpt.getYear());
					endVo.setPeriodMonth(endRpt.getMonth());
					result.add(endVo);
				}
			}else if(startRpt.getYear() == endYear && startRpt.getMonth() == endMonth){
				startVo.setIitDeductionClaimHUuid(startRpt.getIitDeductionClaimHUuid());
				startVo.setBasePersonalInfoUuid(k);
				startVo.setStaffCode(startRpt.getStaffCode());
				startVo.setPeriodYear(startRpt.getYear());
				startVo.setPeriodMonth(startRpt.getMonth());
				result.add(startVo);
			}
		});
		return result;
	}