2016-10-18 41 views
0

我已經使用Spring連接到mongoDb。當使用Criteria創建查詢時,lt/lte不會像他們應該這樣做,即他們正在給出隨機輸出。MongoDb lte/lt查詢意外行爲

我想中的 「X」 一個郵政編碼英里查找商店

查詢創建/執行代碼:

System.out.println("Please Enter your zipCode"); 
      String zipCode = br.readLine(); 
      System.out.println("Enter the distance (miles) to find store"); 
      Integer distance = br.read(); 

      Query query = new Query(); 
      query.addCriteria(Criteria.where("storeDistance").lt(distance).and("storezipCode").is(zipCode)); 

      List<Store>storeList = mongoOperation.find(query, Store.class); 

      if(storeList.isEmpty()){ 
       System.out.println("Oops...no store found nearby...!!"); 
      }else{ 
       for(int idx=0; idx<storeList.size(); idx++){ 
        System.out.println(storeList.get(idx).storeIdentificationumber+"\t"+storeList.get(idx).storeDistance); 
       } 
      } 

Store模式類

package com.storeApp.model; 

import org.springframework.data.annotation.Id; 
import org.springframework.data.mongodb.core.mapping.Document; 

@Document(collection= "stores") 
public class Store { 

    @Id 
    public String storeIdentificationumber; 

    public String storeName; 
    public String storezipCode; 
    public String storeCity; 
    public Integer storeDistance; 

    public Store(){} 

    public Store(String id, String name, String city, String zipCode, Integer distance){ 
     this.storeIdentificationumber = id; 
     this.storeName = name; 
     this.storezipCode = zipCode; 
     this.storeCity = city; 
     this.storeDistance = distance; 
    } 
} 

條目在數據庫:

{ 
     "_id" : "store1", 
     "storeName" : "store One", 
     "storezipCode" : "123", 
     "storeCity" : "city", 
     "storeDistance" : 51 
} 
{ 
     "_id" : "store03", 
     "storeName" : "Store Three", 
     "storezipCode" : "123", 
     "storeCity" : "city", 
     "storeDistance" : 54 
} 

輸入:

Welcome to Store Application....!! 
Please select choice from menu below 
1. Add a Store 
2. Find a Store 
3. Remove a Store 
2 
Please Enter your zipCode 
123 
Enter the distance (miles) to find store 
50 

預期輸出:

Oops...no store found nearby...!! 

實際輸出:

store1 51 

根據標準和數據庫,應該沒有存儲其距離小於50英里但仍有一條記錄正在退回。

回答

1

問題與Integer distance = br.read();假設br是BufferedReader的實例。 read方法只讀取一個字符並給出該字符的整數值。您可以通過打印distance變量進行驗證。

您需要使用readLine並轉換爲使用Integer.parseInt

+0

感謝串號......它的工作。 – anukuls

0

是啊這有點奇怪,事情是如果你想在你的查詢中添加多個選項,你應該不斷添加Criteria,One Criteria不能帶多個字段。

在你的情況下,storezipCode正在從Criteria主字段中刪除storeDistance。

試試這個

Query query = new Query(); 
query.addCriteria(Criteria.where("storeDistance").lt(distance)); 
query.addCriteria(Criteria.where("storezipCode").is(zipCode)); 

所以問題是,在什麼情況下,你會用「和」,你需要監視爲例子,但它不工作,我們希望它的工作方式。