上网搜了半天都没找到能用的,好不容易找到一个记录一下省的自己也忘了
如数据 ( 吐嘲一下,头条的 代码 只显示一行,,太垃圾了,不用代码器了)
{
“_id”:”sdfljkklejrwoefhsdgh”,
“name”:”不知道叫什么”,
“type”:1,
“arr”:[
{“name”:”这不重要”,”price”:5.24},
{“name”:”还是不重要”,”price”:8.42},
{“name”:”更不重要”,”price”:18.28},
]
}
上面的数据,我们如果想要拿到arr的长度
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.unwind(“arr”, “arrIndex”, true));
operations.add(Aggregation.project()
.and(“_id”).as(“_id”)
.and(“name”).as(“name”)
.and(“type”).as(“type”)
.and(“arr”).as(“arr”)
.andExpression(“size(arr)”).as(“arrSize”)
);
operations.add(Aggregation.group(“_id”)
.first(“name”).as(“name”)
.first(“type”).as(“type”)
.first(“arrSize”).as(“arrSize”)
.addToSet(“arr”).as(“arr”)
);
Aggregation agg = Aggregation.newAggregation(operations);
AggregationResults<Map> results = mongoTemplate. aggregate (agg, “集合名称”, Map.class);
这样,就能拿到你要的大小数据了,做个排序什么的,应该还是比较方便的