带有管道聚合的Spring Data MongoDB模板查找

问题描述 投票:0回答:1

关注此Spring Data MongoDB Lookup with Pipeline Aggregation我写了mongoTemplate句子但这不像我想的那样这是我的mongodb sql

db.getCollection('user').aggregate([
{$match:{enterpriseId:"a40ed73d8d704397aaa4e9b4d90c4dd5",type:2}},
{$sort:{name:1}},
{$lookup:
    {
     from: "deviceConfig",
     let: { "device_id": "$id"},
     pipeline:[
          { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$deviceId",  "$$device_id" ] },
                         { $eq: [ "$cfgKey",  "on_off" ] },
                       ]
                    }
                 }
              },
     ],
     as: "config"}},
{ $unwind : { path: "$config" ,preserveNullAndEmptyArrays: true}},
{ $skip:0},
{ $limit:10}])

并且此sql的结果应如下所示enter image description here

根据顶部的网址,我写了mongotemplate

public Response getAllDeviceConfig(String cfgKey, String enterpriseId, int currPage, int pageSize) {    
String lookupQuery =
                    "{ $lookup: {" +
                            "'from': 'deviceConfig'," +
                            "'let': {'device_id': '$id'}," +
                            "'pipeline':[{" +
                            "$match:{$expr:{$and:[" +
                            "{$eq:['deviceId','$$device_id']}," +
                            "{$eq:['$cfgKey','" + cfgKey + "']}]}}," +
                            "}]," +
                            "'as':'config'}}";

            TypedAggregation<UserDevice> typedAggregation = Aggregation.newAggregation(
                    UserDevice.class,
                    match(Criteria.where("enterpriseId").is(enterpriseId).and("type").is(2)),
                    sort(Sort.Direction.ASC, "name"),
                    skip(pageSize * (currPage - 1)),
                    limit(pageSize),
                    new CustomProjectAggregationOperation(lookupQuery),
                    unwind("config", true)
            );
            AggregationResults<UserDevice> list = mongoTemplate.aggregate(typedAggregation, "user", UserDevice.class);
return null;
}

这是我的UserDevice类

@Data
@Document(collection = "user")
public class UserDevice {
    private String id;
    private String name;
    private String nick;
    private int status;
    private JSONObject config;
}

但是返回结果的“ config”始终为“ null”这是我的返回结果,红色的配置不应为nullenter image description here我用想法来查看它创建的最终SQL,但一切似乎都正确enter image description hereenter image description here

是因为我在UserDevice类中的配置类型不正确,或者我的查询字符串sql不正确?我真的很困惑,请帮助我

java mongodb spring-data-jpa spring-data spring-jdbc
1个回答
0
投票
对不起,我敢打扰enter image description here我错过了$!上帝真是太傻了.....
© www.soinside.com 2019 - 2024. All rights reserved.