我正在使用以下聚合管道,并且在Spring Data Mongodb中有一种奇怪的行为。聚合运行良好,直到引发facet
异常的Invalid reference 'producer.fundings.type'!
阶段。
Fields fieldsToBeGroupedTest = Fields.fields()
.and("producerId", "producer.producerId")
.and("name", "producer.name")
.and("fundings", "producer.fundings");
GroupOperation groupOperationTest = group(fieldsToBeGroupedTest);
结果根据
进行投影ProjectionOperation projectionOperationTest = project()
.and("_id.producerId").as("producer.producerId")
.and("_id.name").as("producer.name")
.and("_id.fundings").as("producer.fundings")
.andExclude("_id");
从DEBUG日志记录中,数据库将执行以下聚合
[{
"$group": {
"_id": {
"producerId": "$producer.producerId",
"name": "$producer.name",
"fundings": "$producer.fundings"
}
}
}, {
"$project": {
"producer.producerId": "$_id.producerId",
"producer.name": "$_id.name",
"producer.fundings": "$_id.fundings",
"_id": 0
}
}]
在MongoShell中执行此聚合时,将返回具有以下模式的多个文档:
{
"producer": {
"producerId": "CRYO",
"name": [{
"lang": "en",
"text": "CRYOBS-CLIM"
}],
"fundings": [{
"type": "Organisation",
"acronym": "IRD",
"name": [{
"lang": "en",
"text": "Institut de Recherche pour le Développement"
}]
},
{
"type": "Organisation",
"acronym": "CNRS",
"name": [{
"lang": "en",
"text": "Centre National de la Recherche Scientifique"
}]
}
]
}
}
在流水线的最后阶段,将执行以下FacetOperation,并返回未执行unwind
操作的方式。
FacetOperation facetOperationTest = facet(
unwind("producer.fundings"),
project().and("producer.fundings.type").as("type").and("producer.fundings.acronym").as("name"),
group("name", "type").count().as("count"),
project("count").and("_id.name").as("name").and("_id.type").as("type").andExclude("_id")
).as("fundingAcronymsFacet");
如果在MongoShell中以以下方式执行,则此FacetOperation就像一个超级按钮一样工作:
{
"$facet": {
"fundingAcronymsFacet": [{
"$unwind": "$producer.fundings"
}, {
"$project": {
"type": "$producer.fundings.type",
"name": "$producer.fundings.acronym"
}
}, {
"$group": {
"_id": {
"name": "$name",
"type": "$type"
},
"count": {
"$sum": 1
}
}
}, {
"$project": {
"count": 1,
"name": "$_id.name",
"type": "$_id.type",
"_id": 0
}
}]
}
}
有人遇到过这种意外行为吗?