gpt4 book ai didi

使用管道聚合的 Spring Data MongoDB 查找

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:11 25 4
gpt4 key购买 nike

如何将以下 MongoDB 查询转换为供我的 Java Spring 应用程序使用的查询?我找不到将 pipeline 与提供的 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 中使用 pipeline,而我正在使用的驱动程序版本不支持该功能。

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 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58408140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com