我试图检索具有特定“_id”的文档和具有另一个特定“_id”的单个嵌入文档。
我的文档代表一个目录,它包含一系列课程。
示例数据:
'_id': ObjectId('1111'),
'name': 'example catalog',
...
...
'courses': [
{
'_id': ObjectId('2222'),
'name': 'my course',
...
},
{
....
}
Run Code Online (Sandbox Code Playgroud)
在 mongod 我运行这个聚合查询,并得到我想要的:
db.getCollection('catalogs').aggregate(
{ $match: { '_id': ObjectId('58e8da206ca4f710bab6ef74') } },
{ $unwind: '$courses' },
{ $match: { 'courses._id': ObjectId('58d65541495c851c1703c57f') } })
Run Code Online (Sandbox Code Playgroud)
正如我之前提到的,我已经恢复了单个目录实例,其中包含单个课程实例。
在我的 java repo 中,我试图做同样的事情:
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();
Run Code Online (Sandbox Code Playgroud)
但不幸的是,我有一个“示例目录”的实例,其中包含空的课程数组。
在调试时,我发现里面results有两个返回的 props。第一个是我使用过的,称为mappedResults(代表从 …