小编典典

使用find *()查询时出现Mongodb的Springboot错误

spring-boot

我收到以下错误:

在com.aks.springStorage.SpringStorageApplication.main(SpringStorageApplication.java:22)上[类/:na]

由以下原因引起:org.springframework.data.mongodb.UncategorizedMongoDbException:查询失败,错误代码2和错误消息“字段’locale’在服务器localhost:27017上的{区域设置:“公司”}’中无效;嵌套异常是com.mongodb.MongoQueryException:查询失败,错误代码2,并且错误消息“字段’locale’在以下位置无效:服务器本地主机上的{locale:“
company”}’本地主机:27017

奇怪的是,我没有在公司集合中使用任何类似“ locale”的变量。我能够插入并获得计数,但是findAll *都无法正常工作,并得到相同的错误。

public interface CompanyRepository extends MongoRepository<Company, String> {
    List<Company> findByName(String name);

    @Query("{'contact.address': ?0}")
    List<Company> findByAddress(String address);
}

@Document(collation = "company")
public class Company {
    private int id;
    private String name;
    private List<Product> products;
    private Contact contact;

    public Company(int id, String name, List<Product> products, Contact contact) {
        this.id = id;
        this.name = name;
        this.products = products;
        this.contact = contact;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }
}

// Client code:      
//this is working fine
int count = (int) companyRepo.count();

// Failing Here
companies = companyRepo.findByName("yy");

阅读 388

收藏
2020-05-30

共1个答案

小编典典

@Document(collation="company")

这看起来像是拼写错误,也是造成问题的原因。您尝试设置集合名称,但不是collection使用collation属性:https
:
//docs.mongodb.com/manual/reference/collat​​ion/

正确的注释形式为:

@Document(collection = "company")
public class Company {
    // ...
}

或更简单-因为value是的别名collection

@Document("company")
public class Company {
    // ...
}

您甚至可以完全省略集合名称。在这种情况下,Spring将使用类名作为集合名:

@Document // name of collection wil be "company", as per class name
public class Company {
    // ...
}

最后一个示例是为什么即使没有显式提供集合名称,它也可以用于计数查询等原因。

2020-05-30