[英]Mongodb group then count number of instances separately
我的收藏中有一些与此类似的数据,
{name: one, Status: Unauthorised},
{name: two, Status: Retired},
{name: three, Status: Authorised},
{name: two, Status: Unauthorised},
{name: two, Status: Unauthorised},
{name: two, Status: Retired},
{name: three, Status: Unauthorised},
{name: three, Status: Unauthorised},
{name: one, Status: Retired},
我如何进行聚合以获取在哪里可以获得未经授权和已停用字段的数量?
我希望输出看起来像这样。
{name: one, Retired: 1, Unauthorised: 1,}
{name: two, Retired: 2, Unauthorised: 2,}
{name: three, Retired: 0, Unauthorised: 2,}
我的代码目前看起来像这样,但是这会为我想要的两个状态带回单独的记录
{$match: {Status: {$in:["Un-authorised", "Retired"]}}},
{$group: {_id : {Status:'$Status', machineid:'$name'}, Unauthorised:{$sum :1}}},
{$sort:{Unauthorised:-1}},
{$project : {Status: '$_id.Status', machineid:'$_id.name', Unauthorised : '$Unauthorised', _id : 0}},
这是输出等价物
{name: one, Retired: 1,}
{name: one, Unauthorised: 1,}
{name: two, Retired: 2}
{name: two, Unauthorised: 2,}
{name: three, Retired: 0 }
{name: three, , Unauthorised: 2}
你可以试试,
$match
你的条件$group
按name
和status
并获得总状态的总和$group
仅按name
并推送 k 中的状态和 v 中的值$replaceWith
(K,V)阵列到对象使用,以取代根对象,转换状态$arrayToObject
使用和合并与名称$mergeObjects
db.collection.aggregate([
{
$match: {
Status: { $in: ["Unauthorised", "Retired"] }
}
},
{
$group: {
_id: {
name: "$name",
Status: "$Status"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.name",
status: {
$push: {
k: "$_id.Status",
v: "$count"
}
}
}
},
{
$replaceWith: {
$mergeObjects: [
{ name: "$_id" },
{ $arrayToObject: "$status" }
]
}
}
])
第二个选项,用于修复$group
状态条件,
$group
按名称$cond
创建一个字段Retired
for sum,然后添加一个否则为零$cond
创建一个字段Unauthorised
for sum 如果匹配,则添加一个否则为零
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.