我正在尝试转换我的MongoDB聚合查询:
db.identification.aggregate([
{
$match: {
userId: "b0e644d2-5a0c-4048-abea-6ae17c337e57"
}
},
{
$project: {
status: {
$objectToArray: "$status"
}
}
},
{
$project: {
status: {
$arrayElemAt: ["$status.k", 0]
}
}
},
{
$group: {
_id: "$status",
count: {$sum: 1}
}
},
{
$project: {
_id: 0,
status: {
"name": "$_id",
"count": "$count"
}
}
},
{
$group: {
_id: "counts",
counts: {$addToSet: "$status"}
}
}
])
进入Scala DSL:
collection.aggregate(List(
filter(Document("userId" -> userId)),
project(Document("status" -> Document("$objectToArray" -> "$status"))),
project(Document("status" -> Document("$arrayElemAt" -> List("$status.k" -> 0)))),
group("$status", sum("count", 1)),
project(Document("_id" -> 0, "status" -> Document("name" -> "$_id", "count" -> "$count"))),
group("counts", addToSet("counts", "$status"))
))
但是,当我尝试运行查询时,出现以下错误:
com.mongodb.MongoCommandException: Command failed with error 168: 'Unrecognized expression '$status.k'' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Unrecognized expression '$status.k'", "code" : 168, "codeName" : "InvalidPipelineOperator" }
有没有办法使用预定义的聚合查询,或者有人可以解释我在这里做错了什么?
答案 0 :(得分:0)
看起来可以通过以下方式解决这个问题:
project(Document("status" -> Document("$arrayElemAt" -> List(BsonString("$status.k"), BsonInt32(0)))))
我希望能够提供更清洁的解决方案。看起来隐式转换无法正确处理Int
。