我的数据:
{"_id": "0x026EFF", "Stations": {"MP": false, "AS": true, "RW": true, "FT": true}},
{"_id": "0x026F00", "Stations": {"MP": null, "AS": true, "RW": true, "FT": false}},
{"_id": "0x026F01", "Stations": {"MP": null, "AS": true, "RW": false, "FT": null}},
{"_id": "0x026F02", "Stations": {"MP": null, "AS": null, "RW": true, "FT": false}},
{"_id": "0x026F03", "Stations": {"MP": null, "AS": true, "RW": null, "FT": false}}
这是我的查询
Collection.aggregate([
{"$group": {'_id': None,
'MP': {'$sum': {'$cond': ["$Stations.MP", 1, 0]}},
'AS': {'$sum': {'$cond': ["$Stations.AS", 1, 0]}},
'RW': {'$sum': {'$cond': ["$Stations.RW", 1, 0]}},
'FT': {'$sum': {'$cond': ["$Stations.FT", 1, 0]}}
}
},
{'$project': {'_id': 0}}
])
mongoplayground
我有
[{"AS":4,"FT":1,"MP":0,"RW":3}]
我的问题是我可以重写我的查询吗;MP"AS"RW"FT">?
-
$set
-通过将Stations
从键值对转换为具有k
和v
字段的文档的数组来设置Stations
字段。 -
$unwind
-将Stations
数组反构造为多个文档。 -
$group
—按Stations.k
分组,按条件求和。 -
$group
-按null
分组,将所有文档合并为一个文档,并将根文档推送到data
数组中。 -
$replaceWith
-将输入文档替换为:5.1.
$arrayToObject
-将结果5.1.1中的数组转换为键值对。5.1.1.
$map
-迭代data
数组,并返回一个新数组,其中包含包含k
和v
字段的文档。
db.collection.aggregate([
{
$set: {
Stations: {
$objectToArray: "$Stations"
}
}
},
{
$unwind: "$Stations"
},
{
$group: {
_id: "$Stations.k",
count: {
$sum: {
$cond: {
if: {
$eq: [
"$Stations.v",
true
]
},
then: 1,
else: 0
}
}
}
}
},
{
$group: {
_id: null,
data: {
$push: "$$ROOT"
}
}
},
{
$replaceWith: {
$arrayToObject: {
$map: {
input: "$data",
in: {
k: "$$this._id",
v: "$$this.count"
}
}
}
}
}
])
演示@Mongo Playground