我需要进行聚合查询,
MatchOperation matchOperation = Aggregation.match(new Criteria("age").is(20));
String lookup = "{$lookup: {from: 'race', localField: 'carId',foreignField: 'carId', as: 'result',},},";
String unwind = " {\n" +
" $unwind: {\n" +
" path: \"$result\",\n" +
" },\n" +
" },";
String addField = "{ $addFields: { speed: '$result.raceSpeed', time: '$result.raceResulttime', progress: '$result.progress',},},";
String matchField = " {\n" +
" $match:\n" +
" {\n" +
" time: {\n" +
" $gt: 0,\n" +
" },\n" +
" },\n" +
" },";
String projectField = " {\n" +
" $project: {\n" +
" rank: 0,\n" +
" age: 0,\n" +
" phone: 0,\n" +
" role: 0,\n" +
" carImage: 0,\n" +
" creationDate: 0,\n" +
" gender: 0,\n" +
" _id: 0,\n" +
" result: 0,\n" +
" },\n" +
" },";
SortOperation sortOperation = Aggregation.sort(Sort.Direction.ASC,"time");
Aggregation aggregation = Aggregation.newAggregation(
matchOperation,
new CustomAggregationOperation(lookup),
new CustomAggregationOperation(unwind),
new CustomAggregationOperation(addField),
new CustomAggregationOperation(matchField),
new CustomAggregationOperation(projectField),
sortOperation
);
List<AggResult> outputs= mongoTemplate.aggregate(aggregation, "user",
AggResult.class).getMappedResults();
我需要在比赛字段中处理一些变量,例如
String matchField = " {\n" +
" $match:\n" +
" {\n" +
" time: {\n" +
" $gt: timevariable,\n" + <============== wanna pass timevariable here
" },\n" +
" },\n" +
" },";
我已经尝试过这里的逃生解决方案 在此处输入链接描述但没有成功, 如果有人可以提供帮助,我将不胜感激,谢谢
我的答案是,如果使用本机查询,传递给它的变量是
String iamvairable = "177";
System.out.println(iamvairable);
String projectField = " {\n" +
" $project: {\n" +
" rank: 0,\n" +
" age: "+iamvairable+",\n" +
" phone: 0,\n" +
" role: 0,\n" +
" carImage: 0,\n" +
" creationDate: 0,\n" +
" gender: 0,\n" +
" _id: 0,\n" +
" result: 0,\n" +
" },\n" +
" },";
System.out.println("test string - " + projectField);