将mongoDB查询转换为spring数据查询

时间:2018-12-05 21:24:05

标签: java spring mongodb spring-boot spring-data

我有以下工作查询:

db.shops.aggregate([
{
    $lookup:{
        from: "likedShops",
        localField: "_id",
        foreignField: "shop",
        as: "shops"
    }
},
{ 
    $unwind: { path: "$shops", preserveNullAndEmptyArrays: true }
},
{
    $match: { 'shops.user': ObjectId("5c04b943ff491824b806686a") }
}
])

我正在Spring Boot项目中尝试以下操作,但结果大小为0,应为2:

public void shopList() {
        LookupOperation lookupOperation = LookupOperation.newLookup()
                .from("likedShops")
                .localField("_id")
                .foreignField("shop")
                .as("shops");
        UnwindOperation unwindOperation = Aggregation.unwind("shops", true);

        Aggregation aggregation = Aggregation.newAggregation(unwindOperation, Aggregation.match(Criteria.where("shops.user").is(new ObjectId("5c04b943ff491824b806686a"))), lookupOperation);
        List<Shop> results = mongoTemplate.aggregate(aggregation, "shops", Shop.class).getMappedResults();
        LOGGER.info("Obj Size " + results.size());
    }

1 个答案:

答案 0 :(得分:0)

newAggregation方法的参数顺序很重要,应为:

Aggregation aggregation = Aggregation
                .newAggregation(lookupOperation, unwindOperation, Aggregation.match(Criteria.where("shops.user")
                        .is(new ObjectId(userId))));