如何比较一个列属性的mongo Spring 月份标准

icomxhvb  于 2023-03-16  发布在  Spring
关注(0)|答案(2)|浏览(344)

我如何比较mongo标准中的月份和硬编码值,month标准是以spring格式表示的,而值是以整数格式表示的。
这是我到目前为止,我只是想检查该月份和集团员工ID,如果registrationDate重复

public List<Employees> getEmployees(){
    Query query = new Query();
    query.addCriteria(Criteria.where("registrationDate").is("2"));
    return mongoTemplate.find(query, Visit.class);
    }

但这将返回空值,这是不正确的,因为我有在二月注册的员工,并且数据库中的注册月份以“2023-02-06 00:00:00.000000”格式存储
如有任何建议,我们将不胜感激

qoefvg9y

qoefvg9y1#

我认为您正在寻找类似this one的查询,因此您可以尝试类似以下的操作:

Aggregation aggregation = Aggregation.newAggregation(
    match(Criteria.where("date").month().equalTo(2)));
return mongoTemplate.aggregate(aggregation, "collection", Visit.class).getMappedResults();
4sup72z8

4sup72z82#

您试图将整个日期与月份的值进行比较,但结果不匹配,因此得到0个结果。如果您将日期值存储为字符串,则可以使用$regex,如下所示:

public List<Employees> getEmployees(){
    Query query = new Query();
    query.addCriteria(Criteria.where("registrationDate").regex("^\\d{4}-02-\\d{2}"));
    return mongoTemplate.find(query, Visit.class);
}

Playground link.

相关问题