sql >> Databáze >  >> NoSQL >> MongoDB

Celkové hodnoty ze všech klíčů ve vnořeném dokumentu

V agregačním rámci mongodb neexistuje způsob, jak zacházet s akey uvnitř dokumentu jako s daty, která můžete zkoumat nebo s nimi manipulovat. Řešením je převést to, co zde používáte jako klíče (např. typ ovoce a název obchodu), na hodnoty, jako je tato:

{
    "_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
            }
            ]
        }
    ]
}

To vám umožní snáze pracovat s těmito daty v agregaci:

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}}])

Výstup vypadá takto:

{
    "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
}



  1. MapReduce Shuffling a řazení v Hadoop

  2. nainstalovat redis na instanci aws micro

  3. Použití execPopulate()

  4. Naplnit + agregovat v Mongoose