Mongodb - 使用 addToSet 的项目计数 [英] Mongodb - count of items using addToSet

查看:32
本文介绍了Mongodb - 使用 addToSet 的项目计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按organization 分组并使用$addToSet 来显示与该organization 相关联的不同machineIds.我想获取每个 organizationmachineIds 计数.但是,下面的代码返回所有 machineIds 的计数,而不是不同的计数.有没有另一种方法可以获得唯一的machineIds?

I grouped by organization and used $addToSet to show the distinct machineIds associated with that organization. I would like to get the count of machineIds for each organization. However the code below is returning a count of all machineIds, not the count of distinct ones. Is there another way to get the total unique machineIds?

db.getCollection('newcollections').aggregate([{
    $group: {
    _id: {
        organization: "$user.organization"
    },
    machineId: {
        "$addToSet": "$user.machineId"
    },
    count: {
        $sum: 1
    }
    }
}])

推荐答案

你需要使用 $size 运算符如下:

You need to use $size operator in projection like following:

db.collection.aggregate([{
    $group: {
    _id: {
        organization: "$user.organization"
    },
    machineId: {
        "$addToSet": "$user.machineId"
    }
    }
}, {
    $project: {
    "organization": "$_id.organization",
    "machineId": 1,
    "_id": 0,
    "size": {
        $size: "$machineId"
    }
    }
}])

这篇关于Mongodb - 使用 addToSet 的项目计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆