在完成$facet之后投影数据



完成$facet后,我收到以下输出:

[
{
"confirmed": [
{
"confirmed": 100
}
],
"denied": [
{
"denied": 50
}
],
"pending": [
{
"pending": 20
}
]
}
]

我怎么能把它投射成这样?

[
{
category: "confirmed", count: 100,
category: "denied", count: 50,
category: "pending", count: 20
}
]

我需要水龙头部分,因为要提取这些数字,我必须对相同的数据进行几次匹配。不知道是否还有更好的选择。

谢谢!

您所要求的不是有效的格式。这是一个具有重复关键帧的对象。您可能想要:

[{"confirmed": 100,  "denied": 50, "pending": 20}]

[
{category: "confirmed", count: 100}, 
{category: "denied", count: 50}, 
{category: "pending", count: 20}
]

这两个都是有效的选项

我想你想要第二种选择。如果你想要通用的解决方案,一个选项是:

db.collection.aggregate([
{$project: {res: {$objectToArray: "$$ROOT"}}},
{$project: {
res: {$map: {
input: "$res",
in: {category: "$$this.k", count: {$objectToArray: {$first: "$$this.v"}}}
}}
}},
{$project: {
res: {$map: {
input: "$res",
in: {category: "$$this.category", count: {$first: "$$this.count.v"}}
}}
}},
{$unwind: "$res"},
{$replaceRoot: {newRoot: "$res"}}
])

看看它是如何在操场上工作的例子-通用

如果你想要文字选项,只需使用:

db.collection.aggregate([
{$project: {
res: [
{category: "confirmed", count: {$first: "$confirmed.confirmed"}},
{category: "denied", count: {$first: "$denied.denied"}},
{category: "pending", count: {$first: "$pending.pending"}}
]
}
},
{$unwind: "$res"},
{$replaceRoot: {newRoot: "$res"}}
])

看看它是如何在操场上工作的例子-文字

相关内容

  • 没有找到相关文章

最新更新