Mongodb php:统计一组文档中字段的个数


mongodb php: count the number of field in a set of documents

我正在使用mongodb库的codeigniterhttps://github.com/intekhabrizvi/Codeigniter-mongo-library

下面是我的集合"users"。我想统计用户集合中badge_slug = 100_club的所有徽章。

我试过的是

$this->mongo_db->where(array('badges.badge_slug'=>"100_club"))->count('users');

但是它只给出了100_club的用户数量,不管它不止一次。

{
"_id" : ObjectId("57b83ae9faa76bac338b4579"),
"displayname" : "test",
"email" : "test@gmail.com",
"badges" : [
    {
        "awarded_at" : ISODate("2015-04-21T05:52:06Z"),
        "object_id" : "",
        "badge_slug" : "100_club"
    },
    {
        "awarded_at" : ISODate("2015-04-21T06:12:14Z"),
        "object_id" : "",
        "badge_slug" : "100_club"
    },
    {
        "awarded_at" : ISODate("2015-04-21T07:09:55Z"),
        "object_id" : "",
        "badge_slug" : "reader"
    }
]
}
{
    "_id" : ObjectId("57b83ae9faa76bac338b457a"),
    "displayname" : "test2",
    "email" : "test2@gmail.com",
    "badges" : [
        {
            "awarded_at" : ISODate("2015-04-21T06:44:20Z"),
            "object_id" : "",
            "badge_slug" : "100_club"
        }
    ]
}

请告诉我如何才能得到用户集合中发生的100_club总数

下面是聚合方法,您可以使用 $filter $size 操作符来获取每个文档的计数,然后将所有文档分组以获得总数。这种方法不需要使用 $unwind 操作符来平整化徽章数组,但适用于MongoDB 3.2版本及更高版本:

mongo shell

var ops = [
    {
        "$project" {
            "count": {
                "$size": {
                    "$filter": {
                        "input": "$badges",
                        "as": "badge",
                        "cond": { "$eq": ["$$badge.badge_slug", "100_club"] }
                    }
                }
            }
        }
    },
    {
        "$group": {
            "_id": null,
            "total": { "$sum": "$count" }
        }
    }
];
db.users.aggregate(ops);
PHP

$ops = array(
    array(
        "$project" => array(
            "count" => array(
                "$size" => array(
                    "$filter" => array(
                        "input" => "$badges",
                        "as" => "badge",
                        "cond" => array("$eq" => => array("$$badge.badge_slug", "100_club") )
                    )
                )
            )
        )
    ),
    array(
        "$group" => array(
            "_id" => null,
            "total" => array( "$sum" => "$count" )
        )
    )
);
$this->mongo_db->aggregate("users", $ops);

对于使用 $unwind 操作符在分组之前先平化徽章数组的方法,请遵循以下示例:

mongo shell

db.users.aggregate([
    { "$match": { "badges.badge_slug": "100_club" }
    { "$unwind": "$badges" },
    { "$match": { "badges.badge_slug": "100_club" },
    {
        "$group": {
            "_id": null,
            "total": { "$sum": 1 }
        }
    }
])