我在MongoDB的集合中有一个项目如下:
{
"_id": "MY ID",
"myCollection": [{
"code": "Código 1",
"description": "Descripción entidad 1",
},
{
"code": "Código 2",
"description": "Descripción entidad 2",
},
{
"code": "Código 3",
"description": "Descripción entidad 3",
},
... follows to 19
如果我像这样使用AggregationPipeline:
AggregationPipeline pipeline = getDs().createAggregation(EntidadInfoEntity.class).unwind("myCollection")
.sort(new Sort("myCollection.descripcion", 1)).limit(resultadosPorPagina);
Iterator<EntidadInfoEntity> resultado = pipeline.aggregate(EntidadInfoEntity.class);
while (resultado.hasNext()) {
EntidadInfoEntity entidadInfo = resultado.next();
System.out.println(HerramientasJson.getInstance().convertirAJson(entidadInfo));
}
我总是得到相同的结果:
{"myCollection":[{"code":"Código 1","description":"Descripción entidad 1"}
{"myCollection":[{"code":"Código 1","description":"Descripción entidad 1"}
{"myCollection":[{"code":"Código 1","description":"Descripción entidad 1"}
奇怪的是,如果我调试管道,我会在“阶段”值中得到它:
[{ "$unwind" : "$myCollection"}, { "$sort" : { "myCollection.description" : 1}}, { "$limit" : 25}]
如果我尝试使用:
直接在MongoDB shell下执行它db.myEntities.aggregate([{ "$unwind" : "$myCollection"}, { "$sort" : { "myCollection.description" : 1}}, { "$limit" : 25}])
我得到了正确的结果:
{"myCollection":[{"code":"Código 1","description":"Descripción entidad 1"}]}
{"myCollection":[{"code":"Código 2","description":"Descripción entidad 2"}]}
{"myCollection":[{"code":"Código 3","description":"Descripción entidad 3"}]}
任何想法为什么会这样?我做错了吗?
祝你好运
注意:有些数据已被重写,以便更清楚地显示问题。可能会出现输入错误,但行为就像我解释的那样。
答案 0 :(得分:0)
根据Morphia的团队,解决方案是删除&#34; _id&#34;字段:
Morphia Aggregation Pipeline always returns the same data #932
和
Aggregation unwind function does not behave as expected? #854
如果你不需要_id字段,那很好。但是,如果你仍然需要_id字段(我的情况),你还需要别的东西......