mongodb php:计算子文档中的字段数

时间:2016-09-03 05:24:45

标签: php mongodb codeigniter aggregation-framework codeigniter-3

我正在使用codeigniter和mongodb库https://github.com/intekhabrizvi/Codeigniter-mongo-library

下面是我的收藏"用户"。我想从用户集合中计算所有有用户ID 57b83ae9faa76bac338b4579的badge_slug = 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"
    }
]
}

我所做的是

$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);

因此对于给定的文档,结果应为2。 但它的返回计数适用于所有用户。我应该在哪里提供用户条件?

1 个答案:

答案 0 :(得分:0)

您可以使用$match过滤文档,然后再将这些文档传递到下一阶段。