I have written MongoDB Query for display last one week users count, based lastActive field from Profile collection, lastActive field is date string. Can someone please help me to write corresponding Spring Boot java code of this using SimpleDateFormat class or LocalDate class. Please
var today = new Date();
var lastWeekStart = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
var lastWeekEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
var start = new Date(lastWeekStart.setHours(0,0,0,0));
var end = new Date(lastWeekEnd.setHours(23,59,59,999));
db.Profile.aggregate([
{
"$group": {
"_id": null,
"total": { "$sum": 1 },
"LastWeekUsersList": {
"$sum": {
"$cond": [
{
"$and": [
{ "$gte": [ "$lastActive", start ] },
{ "$lte": [ "$lastActive", end ] }
]
},
1,
0
]
}
}
}
}
])
How to write corresponding spring boot code of this, I am not sure how to write the java equivalent query of mongo db, please help me someone
you can try something like this (not tested)
@Autowired
private MongoOperations mongoOperations;
public MongoOperations getMongoOperations() {
return mongoOperations;
}
....
Instant start = Instant.parse("2020-07-13T10:30:00.000Z");
Instant end = Instant.parse("2020-07-20T10:37:00.000Z");
Criteria criteria = new Criteria().andOperator(
Criteria.where("lastActive").gt(start),
Criteria.where("lastActive").lt(end)
);
ConditionalOperators.Cond sumCond = ConditionalOperators.when(criteria).then(true).otherwise(false);
GroupOperation groupOperation = Aggregation.group().count().as("total").sum(sumCond).as("LastWeekUsersList");
List<MappedType> mappeRes = getMongoOperations().aggregate(Aggregation.newAggregation(
groupOperation
), "myCollecgtion", MappedType.class).getMappedResults();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.