2016-04-15 35 views
0

我正在使用java和MongoDb 3.0,并有一个查询要转换为java代码。将MongoDB3.0查询转换为java

蒙戈DB查询如下:

db.users.find({ $or: [ { updated_at:{ $gt:90, $lte:200}}, { updated_at:{ $gt:350, $lte:400}}, { updated_at:{ $gt:560, $lte:700}} ] }) 

的Java查询该会像下面。

List<Document> orqueryList = new ArrayList<Document>(); 
    List<String> list1 = new ArrayList<String>(); 
    list1.add("90:200"); 
    list1.add("350:400"); 
    list1.add("560:700"); 

    Document greaterQuery = new Document(); 
    Document lessQuery = new Document(); 
    Document lEQuery = new Document(); 
    Document gEQuery = new Document(); 

    for (String time : list1) { 

     String[] updatedAtt = tim.split(":"); 


     gEQuery.put("$gte", Long.parseLong(updatedAtt[0])); 
     lEQuery.put("$lte", Long.parseLong(updatedAtt[1])); 


     greaterQuery.put("updated_at", gEQuery); 
     lessQuery.put("updated_at", lEQuery); 
      orqueryList.add(greaterQuery); 
      orqueryList.add(lessQuery); 

     } 
    query.put("$or", orqueryList); 

但这不是工作作为我的orqueryList名单给我的尺寸3最后的值如下

[文档{{received_at_server =文件{{$ GTE = 560}}}}, Document {{received_at_server = Document {{$ lte = 700}}}}, Document {{received_at_server = Document {{$ gte = 560}}}}, Document {{received_at_server = Document {{$ lte = 700}} }}, Document {{received_at_server = Document {{$ gte = 560}}}}, Document {{received_at_server = Document {{$ lte = 700}}}}]

回答

1
db.users.find({ $or: [ { updated_at:{ $gt:90, $lte:200}}, { updated_at:{ $gt:350, $lte:400}}, { updated_at:{ $gt:560, $lte:700}} ] }) 

查询有两个部分 - 1和的updated_at值$ GT操作和$ LTE 2. OR操作的上述和操作列表。

greaterQuery.put("updated_at", gEQuery); 
    lessQuery.put("updated_at", lEQuery); 
    orqueryList.add(greaterQuery); 
    orqueryList.add(lessQuery); 

    } 
    query.put("$or", orqueryList); 

上面的java代码仅检查OR条件(列表orqueryList)。您正在向OR条件本身添加$ gt和$ lte条件。

尝试以下逻辑:

Document query = new Document(); 
List<String> list1 = new ArrayList<String>(); 
List<Document> andQueryList = new ArrayList<Document>(); 
list1.add("90:200"); 
list1.add("350:400"); 
list1.add("560:700"); 

for (String time : list1) { 
    String[] updatedAtt = time.split(":"); 

    andQueryList.add(new Document("$and", Arrays.asList(new Document("updated_at", new Document("$gte", Long.parseLong(updatedAtt[0]))), 
       new Document("updated_at", new Document("$lte", Long.parseLong(updatedAtt[1])))))); 
} 
query.put("$or", andQueryList); 

查询输出如下(蒙戈查询的当量)

文献{{$或= [文献{{$和= [文献{ {updated_at = Document {{$ gte = 90}}}}, Document {{updated_at = Document {{$ lte = 200}}}}]}}, Document {{and = [Document {{updated_at = Document {{$ gte = 350}}}}, Document {{updated_at = Document {{$ lte = 400}}}}]}}, Document {{and = [Document {{updated_at = Do cument {{$ GTE = 560}}}}, 文件{{=的updated_at文件{{$ LTE = 700}}}}]}}]}}

+0

@Roshan Quadra时但现在给了我最后的值。因为它将最后一个值覆盖到文档中。文档{{$或=文档{{updated_at =文档{{$ gte = 560}}}},文档{{updated_at =文档{{$ lte = 700}}}}]}}} } – Kamini

+0

@Kamini andQuery引用指向最后一个值,因为我们正在为for循环重新创建list对象。我已更新查询片段,该片段将打印预期结果。 –