mongodb中$where查询功能非常强大,不过效率低,这里介绍一下$where的使用方法
db.getCollection('rest.modules.entity.TestCase').find({$where: function () { var result=true; var selectTarger='ffffe10183c3e1ff'; var temp = this.fingerCode; var different = 0; for(var i=0;i<16;i++){ if (selectTarger.charAt(i)!=temp.charAt(i)){ different++; } } if (different==0){ result = true; }else if (different <= 5){ result = true; }else{ result=false; } return result; } }).limit(10);
用java mongo driver调用
BasicDBObject totalQuery=new BasicDBObject(); StringBuilder sb=new StringBuilder(); sb.append("function () { var result=true;"); sb.append("var selectTarger='"+fingerCode+"';"); sb.append("var temp = this."+whereT.getFingerCodeField()+";"); sb.append("var different = 0;"); sb.append("for(var i=0;i<16;i++){"); sb.append("if (selectTarger.charAt(i)!=temp.charAt(i)){"); sb.append("different++;"); sb.append("}"); sb.append("}"); sb.append("if (different==0){"); sb.append("result = true;"); sb.append("}else if (different <= 5){"); sb.append("result = true;"); sb.append("}else{"); sb.append("result=false;"); sb.append("}return result;}"); totalQuery.append(QueryOperators.WHERE, sb.toString()); FindIterable<Document> fiList = collection.find(totalQuery).limit(10);