MongoDb lte/ lt查询异常



我已经连接到mongoDb使用Spring。当使用Criteria创建查询时,lt/lte的行为不应该像它们应该的那样,即它们给出随机输出。

我想查找邮政编码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);
                }
            }

存储模型类

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;
    }
}

Entries in Database:

{
        "_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英里的商店,但仍然返回一条记录。

问题是Integer distance = br.read();假设br是BufferedReader的实例。read方法只读取单个字符并给出该字符的整数值。您可以通过打印distance变量来验证。

您需要使用readLine并使用Integer.parseInt转换字符串数

是的,这有点奇怪,事情是如果你想在你的查询中添加多个选项,你应该不断添加标准,一个标准不能包含多个字段。

在您的示例中,storezipCode正在从Criteria首席字段中删除storeDistance。

Try this

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

所以问题是在什么情况下你会使用'and',你需要寻找例子,但它并没有按照我们想要的方式工作

最新更新