2016-04-15 37 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對象。我已更新查詢片段,該片段將打印預期結果。 –