按计数对集合中没有键的查询中的"True"进行分组



我的数据:

{"_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">

  1. $set-通过将Stations从键值对转换为具有kv字段的文档的数组来设置Stations字段。

  2. $unwind-将Stations数组反构造为多个文档。

  3. $group—按Stations.k分组,按条件求和。

  4. $group-按null分组,将所有文档合并为一个文档,并将根文档推送到data数组中。

  5. $replaceWith-将输入文档替换为:

    5.1.$arrayToObject-将结果5.1.1中的数组转换为键值对。

    5.1.1.$map-迭代data数组,并返回一个新数组,其中包含包含kv字段的文档。

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

最新更新