簡體   English   中英

MongoDB聚合:如何根據條件獲取列數

[英]MongoDB aggregation: How can I get a count of columns based on a criteria

我有以下文件:

{ "col1": "camera", "fps": 1, "lat": 3 },
{ "col1": "camera", "fps": 3, "lat": 2 }
{ "col1": "camera", "foo": 9, "bar": 7 }
{ "col1": "camera", "bar": 8, "bar": 1 }
{ "col1": "camera", "check": 4, "lat": 3 }

我如何獲得以下信息:

{ "fps": 2, "lat": 3, "bar": 3, "check": 1, "foo": 1 }

其中每個值都是每個鍵的出現次數(計數)(fps出現2,foo,出現一次,依此類推)

骨料

如果事先知道密鑰,這里是一個解決方案(我將其稱為收藏cameras ):

 db.cameras.aggregate([
{
    $project: {
        _id: 1,
        fps: {
            $ifNull: [ "$fps", 0 ]
        },
        lat: {
            $ifNull: [ "$lat", 0 ]
        },
        bar: {
            $ifNull: [ "$bar", 0 ]
        },
        foo: {
            $ifNull: [ "$foo", 0 ]
        },
        check: {
            $ifNull: [ "$check", 0 ]
        }
    }
},
{
    $project: {
        _id: 1,
        fps: {
            $cond: [ { $eq: [ "$fps", 0 ] } , 0, 1 ]
        },
        lat: {
            $cond: [ { $eq: [ "$lat", 0 ] } , 0, 1 ]
        },
        bar: {
            $cond: [ { $eq: [ "$bar", 0 ] } , 0, 1 ]
        },
        foo: {
            $cond: [ { $eq: [ "$foo", 0 ] } , 0, 1 ]
        },
        check: {
            $cond: [ { $eq: [ "$check", 0 ] } , 0, 1 ]
        }
    }
},
{
    $group: {
        _id: null,
        fps: {
            $sum: "$fps"
        },
        lat: {
            $sum: "$lat"
        },
        bar: {
            $sum: "$bar"
        },
        foo: {
            $sum: "$foo"
        },
        check: {
            $sum: "$check"
        }
    }
}
])

結果:

{
    "result" : [
        {
            "_id" : null,
            "fps" : 2,
            "lat" : 3,
            "bar" : 2,
            "foo" : 1
        }
    ],
    "ok" : 1
}

MapReduce

如果鍵未知,則另一個解決方案是mapReduce:

db.cameras.mapReduce(
    function() {
        var keys = Object.keys(this);
        keys.forEach(function(key) {
            emit(key, 1);
        });
    },
    function(key, values) {
        return Array.sum(values);
    },
    {
        query: {},
        out: {
            inline: 1
        }
    }
)

結果:

{
    "results" : [
        {
            "_id" : "_id",
            "value" : 5
        },
        {
            "_id" : "bar",
            "value" : 2
        },
        {
            "_id" : "check",
            "value" : 1
        },
        {
            "_id" : "col1",
            "value" : 5
        },
        {
            "_id" : "foo",
            "value" : 1
        },
        {
            "_id" : "fps",
            "value" : 2
        },
        {
            "_id" : "lat",
            "value" : 3
        }
    ],
    "timeMillis" : 1,
    "counts" : {
        "input" : 5,
        "emit" : 19,
        "reduce" : 5,
        "output" : 7
    },
    "ok" : 1,
}

但是結果並不完全相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM