问题描述
如何将下面的 MongoDB 操作写入 Java Springboot 代码中?
db.collection.aggregate({
"$group": {
_id: {
$trim: {
input: "$name"
}
},doc: {
"$first": "$$ROOT",}
}
},{
"$replaceRoot": {
"newRoot": "$doc"
}
})
解决方法
希望您使用的是 mongo 模板。您可以使用 BSON 方法。 TRICK TO CONVERT MONGO SHELL QUERY
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,Object.class).getMappedResults();
}