希望您使用的是 mongo 模板。您可以使用 BSON 方法。转换 MONGO SHELL 查询的技巧
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
p-> new Document("$group",
new Document("_id",
new Document("$trim",
new Document("input","$name")
)
).append("doc",
new Document("$first","$$ROOT")
)
),
replaceRoot("doc")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
但你也可以试试这个。请确保这是有效的
public List<Object> test() {
Aggregation.newAggregation(
group("$_id".trim()).first("$$ROOT").as("doc"),
replaceRoot("doc")
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}