我有这个样本mongodb文件-
{
_id: 5db85ee97d9fb13ead4fc54c
applId: 5d48f34f7d9fb10ce171f905
fileId: "dd386cf7-4139-45c2-9853-cbb126621b51"
job: Object
country: "US"
fullName: "abcd xyz"
htmlWordCount: 2766
textWordCount: 1867
rchilliTextWordCount: 2840
deleted: 0
dateEntered: 2019-10-29 15:46:49.237
dateModified: 2019-10-29 15:46:49.237
}
我想在罗盘中建立查询,以便在输出中包含以下字段-
{
_id: 5db85ee97d9fb13ead4fc54c
country: "US"
fullName: "abcd xyz"
htmlWordCount: 2766
textWordCount: 1867
rchilliTextWordCount: 2840
winner: "rchilliTextWordCount"
}
请注意,它有一个名为“ winner”的新字段,该字段总是返回最大字数的列(3"htmlWordCount", "textWordCount", "rchilliTextWordCount"
列之内)。此新列"winner"
将在运行时根据查询生成。同样,此查询在上过滤country = "US"
。
如何在MongoDB Compass中执行此操作,或者聚合管道应该是什么样?
db.collection.aggregate([
{
$match: {
country: "US"
}
},
{
$project: {
country: 1,
fullName: 1,
htmlWordCount: 1,
textWordCount: 1,
rchilliTextWordCount: 1,
winner: {
$switch: {
branches: [
{
case: {
$and: [
{
$gt: [
"$htmlWordCount",
"$textWordCount"
]
},
{
$gt: [
"$htmlWordCount",
"$rchilliTextWordCount"
]
}
]
},
then: "htmlWordCount"
},
{
case: {
$and: [
{
$gt: [
"$textWordCount",
"$htmlWordCount"
]
},
{
$gt: [
"$textWordCount",
"$rchilliTextWordCount"
]
}
]
},
then: "textWordCount"
},
{
case: {
$and: [
{
$gt: [
"$rchilliTextWordCount",
"$htmlWordCount"
]
},
{
$gt: [
"$rchilliTextWordCount",
"$textWordCount"
]
}
]
},
then: "rchilliTextWordCount"
}
],
default: "No winners"
}
}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句