gpt4 book ai didi

具有管道聚合的 Spring Data MongoDB 查找

转载 作者:可可西里 更新时间:2023-11-01 09:33:28 26 4
gpt4 key购买 nike

如何将以下 MongoDB 查询转换为我的 Java Spring 应用程序要使用的查询?我找不到通过提供的 lookup 使用 pipeline 的方法方法。

这是我试图转换的查询。我还想指出,我没有使用 $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/51107626/

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