MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Gesamtwerte aller Schlüssel im Filialdokument

Es gibt im Mongodb-Aggregationsframework keine Möglichkeit, einen Schlüssel innerhalb eines Dokuments als Daten zu behandeln, die Sie untersuchen oder manipulieren können. Eine Problemumgehung besteht darin, das, was Sie hier als Schlüssel verwenden (z. B. Obstsorte und Ladenname), in Werte wie diese umzuwandeln:

{
    "_id" : "doc1",
    "stores":[
        {
            // store name is a value
            "name":"store_A",
            "inventory": [
            {
                // so is fruit type
                "type" : "apple",
                "count" : 50
            },
            {
                "type" : "orange",
                "count" : 20
            }
            ]
        },
        {
            "name": "store_B",
            "inventory": [
            {
                "type" : "orange",
                "count" : 15
            }
            ]
        }
    ]
}

Dadurch können Sie einfacher mit diesen Daten aggregiert arbeiten:

db.coll.aggregate([
    // split documents by store name
    {$unwind:"$stores"},
    // split documents further by fruit type
    {$unwind:"$stores.inventory"},
    // group documents together by store/fruit type, count quantities of fruit
    {$group:{"_id":{"store":"$stores.name", "fruit":"$stores.inventory.type"},
             "count":{$sum:"$stores.inventory.count"}}},
    // reformat the data to look more like your specification
    {$project:{
        "store":"$_id.store",
        "fruit":"$_id.fruit",
        "_id":0,
        "count":1}}])

Die Ausgabe sieht folgendermaßen aus:

{
    "result" : [
        {
            "count" : 15,
            "store" : "store_B",
            "fruit" : "apple"
        },
        {
            "count" : 15,
            "store" : "store_B",
            "fruit" : "orange"
        },
        {
            "count" : 30,
            "store" : "store_A",
            "fruit" : "orange"
        },
        {
            "count" : 50,
            "store" : "store_A",
            "fruit" : "apple"
        }
    ],
    "ok" : 1
}