我正在Robo3T中进行此聚合:
db.getCollection('Tweets').aggregate([
{"$match": {"ownerId": "5c8d2ce116c7f85377df590a"}}
, {"$match": {"topic": "topic_A"}}
, {"$match": {"timestamp" : { "$gte" : ISODate("2020-02-01T00:00:00.000Z")
, "$lte" : ISODate("2020-02-05T23:59:59.000Z")
}
}
}
,{"$count": "totalData"}
])
文档总数为5742。 现在,我正在用MongoDB驱动程序编写的一个简短程序中进行相同的聚合
这是代码:
public void countMonthData() {
LocalDateTime start = YearMonth.now().atDay(1).atStartOfDay();
LocalDateTime end = YearMonth.now().atDay(5).atStartOfDay().plusSeconds(86399);
MatchOperation matchOperation = Aggregation.match(new Criteria("ownerId").is("5c8d2ce116c7f85377df590a"));
MatchOperation matchTopic = Aggregation.match(new Criteria("topic").is("topic_A"));
MatchOperation matchDates = Aggregation.match(new Criteria("timestamp").gte(start).lte(end));
Aggregation agg = Aggregation.newAggregation(matchOperation, matchTopic, matchDates);
System.out.println(agg);
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Tweets.class, Document.class);
System.out.println("size: " + result.getMappedResults().size());
}
当我打印从汇总中检索到的文档数时,我得到了5100个文档
为什么会有不同的结果?
最后找到错误,我更改了变量start和end的时区,但是由于某些原因,MongoDB不接受新的时区,我必须使用以下配置类为我的项目更改jvm中的时间:
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimeZone;
@Configuration
public class LocaleConfig {
@PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Date in UTC: " + new Date().toString());
}
}