[英]Mongodb in java , how to use date ranges in the aggregates function
I have the following code for filtering based on sex and then grouping based on employee_id, along with an extra field that does the sum for total of days.我有以下代码用于根据性别进行过滤,然后根据employee_id 进行分组,以及一个额外的字段,用于计算总天数。
collection.aggregate(
Arrays.asList(
Aggregates.match(Filters.eq("$sex","male")),
Aggregates.group("$employee_id", sum("total", "$days")),
)
).forEach(printBlock);
In this query how do I add a date range to match for example - greater than (some date) and less than (some date).在此查询中,如何添加日期范围以匹配例如 - 大于(某个日期)和小于(某个日期)。 Also which would be the right format of date to use like in java.util.Date or something else.
这也是在 java.util.Date 或其他东西中使用的正确日期格式。 I found similar questions but nothing in 2020 where there may be an updated part for doing this in an easier way.
我发现了类似的问题,但在 2020 年没有发现任何可能有更新的部分以更简单的方式执行此操作。 Also would there be a way to generate a query without this format and just filter by date range and group by some value.
还有一种方法可以生成没有这种格式的查询,只需按日期范围过滤并按某个值分组。
the json example
{
"employee_id": "GX078333",
"sex": "male",
"days": 5,
"date": {
"$date": "2020-06-01T07:33:50.796Z"
},
}
You can match multiple values using Filters.and(Bson, Bson, ...)
or Filters.and(List<Bson>)
Reference您可以使用
Filters.and(Bson, Bson, ...)
或Filters.and(List<Bson>)
参考匹配多个值
I hope you know that date must be an array/list of dates.我希望您知道日期必须是日期的数组/列表。
So, to provide an Example.所以,提供一个例子。
cDateRang
is an ArrayList
with your Dates which should match. cDateRang
是一个ArrayList
,您的日期应该匹配。
eg例如
ArrayList<Date> cDateRange = new ArrayList<>();
cQueryFields.add(Filters.in("date.mydatearray", cDateRange));
//
Bson cQuery = Filters.and(cQueryFields);
//
ArrayList<Bson> cQueryList = new ArrayList<>();
cQueryList.add(Aggregates.match(cQuery));
//
cQueryList.add(Aggregates.match(cQuery));
AggregateIterable<Document> cResult = cMongoDatabase.getCollection("your collection Name").aggregate(pFilter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.