【发布时间】:2017-04-10 14:57:02
【问题描述】:
我正在尝试检索具有特定“_id”的文档和具有另一个特定“_id”的单个嵌入文档。
我的文档是一个目录,它包含一系列课程。
示例数据:
'_id': ObjectId('1111'),
'name': 'example catalog',
...
...
'courses': [
{
'_id': ObjectId('2222'),
'name': 'my course',
...
},
{
....
}
在 mongod 中我运行这个聚合查询,然后得到我想要的:
db.getCollection('catalogs').aggregate(
{ $match: { '_id': ObjectId('58e8da206ca4f710bab6ef74') } },
{ $unwind: '$courses' },
{ $match: { 'courses._id': ObjectId('58d65541495c851c1703c57f') } })
正如我之前提到的,我已经获得了包含单个课程实例的单个目录实例。
在我的 java 存储库中,我尝试做同样的事情:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where(Catalog.ID_FIELD).is(catalogId)),
Aggregation.unwind(Catalog.COURSES_FIELD, true),
Aggregation.match(Criteria.where(Catalog.COURSES_FIELD + '.' + Course.ID_FIELD).is(embeddedCourseId))
);
AggregationResults<Catalog> results = mongoTemplate.aggregate(aggregation,
Catalog.class, Catalog.class);
List<Catalog> catalog = results.getMappedResults();
但不幸的是,我有一个“示例目录”实例,其中包含空的课程数组。
在调试的时候,我发现在results里面,有两个props返回了。
第一个是我用过的,叫做mappedResults(代表从mongoDB返回的转换对象)——包含一个空的课程数组。
另一个是rawResults,(表示数据为DBObject) - 包含我查询的具体课程
我的 Catalog 类包含一个 ArrayList(如果有什么不同的话)。
请帮助并让我知道我应该怎么做才能正确转换结果,或者如果我在代码中做错了什么。
【问题讨论】:
标签: java spring mongodb aggregation-framework