Spring MongoDB MongoTemplate聚合查询,如何返回List <list <object>&gt;

时间:2017-06-16 10:27:04

标签: java spring mongodb spring-data-mongodb

我徒劳无功,现在向群众提问。

  • 我有GpsRecord的集合,每个GpsRecord属于TrackRecord
  • 每个GpsRecord都会ObjectId引用其父TrackRecord
  • 我想根据GpsRecord
  • 列表查询TrackRecord.ids集合

从这个查询中我想从MonogDB中的聚合查询返回List<List<GpsRecord>>。我的问题是如何在outputType中正确定义.aggregate(agg, GpsRecord.class, List<List<GpsRecord>>)参数?

@Repository
public class GpsRepositoryImpl implements GpsRepositoryCustom {

    private final MongoTemplate _mongoTemplate;

    @Autowired
    public GpsRepositoryImpl(MongoTemplate mongoTemplate) {
        _mongoTemplate = mongoTemplate;
    }

    @Override
    public List<List<GpsRecord>> aggregate(List<ObjectId> ids) {
        MatchOperation match = getMatchOperation(ids);
        GroupOperation group = getGroupOperation();
        Aggregation agg = Aggregation.newAggregation(match, group);

        return _mongoTemplate
                   .aggregate(agg, GpsRecord.class, List<List<GpsRecord>>)
                   .getMappedResults();
    }

    private MatchOperation getMatchOperation(List<ObjectId> ids) {
        Criteria criteria = Criteria.where("trackRecord.id").in(ids);

        return new MatchOperation(criteria);
    }

    private GroupOperation getGroupOperation() {
        GroupOperation agg = Aggregation.group("trackRecord.id");

        return agg;
    }

}

修改

GpsRecord的示例

{
    "_id": ObjectId("593d382c5b3ae715b2cac03d"),
    "_class": "gps",
    "location": {
        "type": "Point",
        "coordinates": [116.315148, 39.984538]
    },
    "dateTime": ISODate("2008-10-23T02:54:40Z"),
    "trackRecord": DBRef("trackRecords", ObjectId("593d382b5b3ae715b2cac029"))
}

TrackRecord的示例

{
    "_id": ObjectId("593d382b5b3ae715b2cac029"),
    "_class": "track",
    "name": "20081117155223.plt",
    "bbox": {
        "type": "Polygon",
        "coordinates": [[[116.31949,39.999686],[116.325796,39.999686],[116.325796,40.009678],[116.31949,40.009678],[116.31949,39.999686]]]
    }
}

TrackRecord由许多GpsRecord个对象组成,就像数千个或更多对象一样。

因此,基于List TrackRecord._id我希望返回List List<GpsRecord>

1 个答案:

答案 0 :(得分:0)

你想要这样的聚合:

db.GpsRecord.aggregate([
    {$group:{_id:"trackRecord.$id", ...}}
])
  

警告:管道无法对以下类型的值进行操作:二进制,符号,MinKey,MaxKey, DBRef ,代码和CodeWScope

但是,如果您使用MongoDB&gt; = 3.4.4,则会有一个新的聚合命令$objectToArrayDBRef转换为数组并允许您对其进行分组。

https://docs.mongodb.com/manual/release-notes/3.4/#apr-21-2017