使用流水线聚合的Spring Data MongoDB查找
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用流水线聚合的Spring Data MongoDB查找,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2492字,纯文字阅读大概需要4分钟。
内容图文
如何将以下MongoDB查询转换为我的Java Spring应用程序使用的查询?我找不到使用提供的lookup方法使用管道的方法.
这是我试图转换的查询.我还想注意,我没有使用$unwind,因为我希望deliveryZipCodeTimings作为返回对象中的分组集合保留.
db.getCollection('fulfillmentChannel').aggregate([
{
$match: {
"dayOfWeek": "SOME_VARIABLE_STRING_1"
}
},
{
$lookup: {
from: "deliveryZipCodeTiming",
let: { location_id: "$fulfillmentLocationId" },
pipeline: [{
$match: {
$expr: {
$and: [
{$eq: ["$fulfillmentLocationId", "$$location_id"]},
{$eq: ["$zipCode", "SOME_VARIABLE_STRING_2"]}
]
}
}
},
{
$project: { _id: 0, zipCode: 1, cutoffTime: 1 }
}],
as: "deliveryZipCodeTimings"
}
},
{
$match: {
"deliveryZipCodeTimings": {$ne: []}
}
}
])
解决方法:
基于@dnickless给出的信息,我能够解决这个问题.我将发布完整的解决方案,希望它能在未来帮助其他人.
我正在使用mongodb-driver:3.6.4
首先,我必须创建一个自定义聚合操作类,以便我可以传入一个自定义的JSON mongodb查询,以便在聚合操作中使用.这将允许我在$lookup中使用管道,而我正在使用的驱动程序版本不支持该管道.
public class CustomProjectAggregationOperation implements AggregationOperation {
private String jsonOperation;
public CustomProjectAggregationOperation(String jsonOperation) {
this.jsonOperation = jsonOperation;
}
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
return aggregationOperationContext.getMappedObject(Document.parse(jsonOperation));
}
}
既然我们能够将自定义JSON查询传递到我们的mongodb spring实现中,剩下的就是将这些值插入到TypedAggregation查询中.
public List<FulfillmentChannel> getFulfillmentChannels(
String SOME_VARIABLE_STRING_1,
String SOME_VARIABLE_STRING_2) {
AggregationOperation match = Aggregation.match(
Criteria.where("dayOfWeek").is(SOME_VARIABLE_STRING_1));
AggregationOperation match2 = Aggregation.match(
Criteria.where("deliveryZipCodeTimings").ne(Collections.EMPTY_LIST));
String query =
"{ $lookup: { " +
"from: 'deliveryZipCodeTiming'," +
"let: { location_id: '$fulfillmentLocationId' }," +
"pipeline: [{" +
"$match: {$expr: {$and: [" +
"{ $eq: ['$fulfillmentLocationId', '$$location_id']}," +
"{ $eq: ['$zipCode', '" + SOME_VARIABLE_STRING_2 + "']}]}}}," +
"{ $project: { _id: 0, zipCode: 1, cutoffTime: 1 } }]," +
"as: 'deliveryZipCodeTimings'}}";
TypedAggregation<FulfillmentChannel> aggregation = Aggregation.newAggregation(
FulfillmentChannel.class,
match,
new CustomProjectAggregationOperation(query),
match2
);
AggregationResults<FulfillmentChannel> results =
mongoTemplate.aggregate(aggregation, FulfillmentChannel.class);
return results.getMappedResults();
}
内容总结
以上是互联网集市为您收集整理的使用流水线聚合的Spring Data MongoDB查找全部内容,希望文章能够帮你解决使用流水线聚合的Spring Data MongoDB查找所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。