我正在根据我在Mongo中拥有的数据,根据文件的最后访问时间对文件集合进行分组。
但是我不确定如何从组操作中返回更多文档。
如何检索包含每个分组下所有信息的文档?
例如,我现在要返回:
[
{
"year": [
2020
],
"month": [
2
],
"week": [
7
],
"day": [
2
],
"results": [
"filename-1",
"filename-2"
]
}
]
我只将文件名恢复到基本数组中。我想要的是文档,而不仅仅是名称。
我用来在上面创建结果的代码
public void groupTest() {
final String dateField = "lastAccessTime";
final LocalDate now = LocalDate.now();
final LocalDate firstDay = now.with(firstDayOfYear());
final LocalDate lastDay = now.with(lastDayOfYear());
final Criteria criteria =
new Criteria().andOperator(where(dateField).gte(firstDay), where(dateField).lte(lastDay));
final ProjectionOperation dateProjection =
project()
.and("_id")
.as("id")
.and("name")
.as("name")
.and("absolutePath")
.as("absolutePath")
.and(dateField)
.extractYear()
.as("year")
.and(dateField)
.extractMonth()
.as("month")
.and(dateField)
.extractWeek()
.as("week")
.and(dateField)
.extractDayOfWeek()
.as("day");
final GroupOperation groupBy =
group("year", "month", "week", "day")
.addToSet("name")
.as("results");
final Aggregation aggregation =
newAggregation(
match(criteria),
dateProjection,
groupBy,
sort(Sort.Direction.ASC, "year", "month", "week", "day"));
}
我希望我的结果值更像:
[
{
"year": [
2020
],
"month": [
2
],
"week": [
7
],
"day": [
2
],
"results": [
{
"id": "123",
"filename": "filename-1",
"size": 30000
},
{
"id": "456",
"filename": "filename-2",
"size": 30000
}
]
}
]
非常感谢您的帮助
GroupOperation group = Aggregation
.group("year", "month", "week", "day")
.addToSet(new Document("id", "$id")
.append("filename", "$name")
.append("size", "$size"))
.as("results");
注意:确保将size
字段包括在dateProjection
阶段中。