java - 将mongodb的聚合查询转换为spring boot
问题描述
我有一个工作正常的 mongodb 查询
db.user.aggregate([
{
"$project": {
"data": {
"$objectToArray": "$$ROOT"
}
}
},
{
$unwind: "$data"
},
{
"$match": {
"data.v": {
$regex: "Mohit Chandani"
}
}
}
])
基本上,获取所有具有 Mohit Chandani 值的文档,这是输出:
{ "_id" : "b387d728-1feb-45b6-bdec-dafdf22685e2", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "8e35c497-4296-4ad9-8af6-9187dc0344f7", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "c38b6767-6665-46b8-bd29-645c41d03850", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
我需要为我的 Spring Boot 应用程序转换此查询,并且我正在编写以下内容:-
Aggregation aggregation = Aggregation.newAggregation(Aggregation.project(Aggregation.ROOT), Aggregation.match(Criteria.where(connectionRequest.getWord())));
在 Spring-Data 中进行长聚合时,了解采用哪种方法会很有帮助。
解决方案
这可能会对您有所帮助,希望您MongoTemplate
用于聚合。
@Autowired
private MongoTemplate mongoTemplate;
上面脚本的代码是
public List<Object> test() {
Aggregation.newAggregation(
project().and(ObjectOperators.valueOf(ROOT).toArray()).as("data"),
unwind("data"),
match(Criteria.where("data.v").regex("Mohit Chandani")
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
我不确定project()
上面的代码是否有效,因为我还没有尝试过。我从Spring 数据 mongodb中引用它
如果它不起作用,这肯定会起作用。Spring 数据中不支持很少的操作,例如$addFields
,$filter
.. 所以我们做了一个技巧来转换
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
p-> new Document("$project",
new Document("data",
new Document("$objectToArray","$$ROOT")
)
),
unwind("data"),
match(Criteria.where("data.v").regex("Mohit Chandani"))
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
推荐阅读
- html - 居中下拉内容?
- node.js - 如果 mongodb 中不存在字段,则更新所有嵌套数组记录
- java - 如何为*压力测试*模拟不良网络以及要模拟哪些方面?
- mysql - Laravel 雄辩的查询与条件下另一个表中的值的总和
- user-interface - 颤振 | 如何创建具有以下内容的容器,以及如何在小部件周围/容器内绘制自定义边框
- javascript - 在 JavaScript 中:如何向现有函数添加参数?
- nginx - NGInx log_format 从 $http_referrer 中删除任何敏感数据
- python - Pandas Groupby-根据组变化添加顺序元素
- css - 为什么我的 CSS 网格会创建四列而不是一列?
- javascript - Webpack 加载器错误:您可能需要额外的加载器来处理这些加载器的结果